为什么这个 Mongoose 查询返回预期结果,但我无法利用它的属性?
我想检查请求的文章页面是否实际上是经过 Passportjs req.isAuthenticated() 函数身份验证的用户的文章之一。 我试图使用 $elemMatch 来实现这一点,它通过 Passport.authenticate() 方法记录存储在 req.user 中的相同用户,但是当我记录 user._id 时,它给了我未定义的信息。这是为什么?
const express = require('express');
const http = require('http');
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require('passport');
const passportLocalMongoose = require('passport-local-mongoose');
const app = express();
const server = http.createServer(app);
mongoose.connect("mongodb://localhost:27017/userDB");
const articleSchema = new mongoose.Schema({
name: String
});
const userSchema = new mongoose.Schema({
email: String,
password: String,
articles: [articleSchema]
});
const User = new mongoose.model("User", userSchema);
const Article = new mongoose.model("Article", articleSchema);
app.get('/:articlename/:articleId', (req, res) => {
let articleName = req.params.articlename,
articleId = req.params.articleId;
if (req.isAuthenticated()) {
console.log(req.user); // prints the authenticated user
User.find({ articles: { $elemMatch: { "_id": articleId, "name":articleName } } }, function(err, user){
if(err){
console.log(err);
}else{
console.log("This article belongs to " + user); // outputs the expected user
console.log("This article belongs to user with an id " + user._id); // outputs undefined
}
}
)
} else {
console.log('Not Authenticated!');
}
});
I want to check whether the requested article page is actually one of the articles of the user who's been authenticated by passportjs req.isAuthenticated() function.
I'm trying to use $elemMatch to achieve that and it logs the same user that's stored in req.user by passport.authenticate() method but when I log user._id it gives me undefined. Why is that?
const express = require('express');
const http = require('http');
const mongoose = require("mongoose");
const session = require("express-session");
const passport = require('passport');
const passportLocalMongoose = require('passport-local-mongoose');
const app = express();
const server = http.createServer(app);
mongoose.connect("mongodb://localhost:27017/userDB");
const articleSchema = new mongoose.Schema({
name: String
});
const userSchema = new mongoose.Schema({
email: String,
password: String,
articles: [articleSchema]
});
const User = new mongoose.model("User", userSchema);
const Article = new mongoose.model("Article", articleSchema);
app.get('/:articlename/:articleId', (req, res) => {
let articleName = req.params.articlename,
articleId = req.params.articleId;
if (req.isAuthenticated()) {
console.log(req.user); // prints the authenticated user
User.find({ articles: { $elemMatch: { "_id": articleId, "name":articleName } } }, function(err, user){
if(err){
console.log(err);
}else{
console.log("This article belongs to " + user); // outputs the expected user
console.log("This article belongs to user with an id " + user._id); // outputs undefined
}
}
)
} else {
console.log('Not Authenticated!');
}
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 .exec() 会触发查询并返回一个可用的 Promise,在 .exec() 中添加回调并不是等待 Promise 得到解析的有效方法 Mongoose 文档 它用于
Mongoose 异步操作,如 .save() 和查询,返回thenables。
这意味着如果您使用 async/await,您可以执行诸如 MyModel.findOne({}).then().catch() 和 wait MyModel.findOne({}).exec() 之类的操作。
调用 .exec() 后,它会执行您的查询并返回一个 Promise,您可以在异步函数中等待,方法是执行类似
Which 会等待 Promise 得到解决并为您提供结果/处理错误的操作。
使用await而不使用.exec()也是一种有效的方法,更多信息可以在以下位置找到:应该将 exec() 与 wait 一起使用吗?
否则,您可以使用 thenable 方法,该方法将执行查询并在 .then() 中为您提供结果.catch()。
示例:
为了更好地理解,我强烈建议查看 Mongoose Promises 文档页面
Using .exec() triggers a query and returns a Promise which is thenable, adding a callback in .exec() is not a valid way to wait for the promise to be resolved as per Mongoose documentation it is used for
Mongoose async operations, like .save() and queries, return thenables.
This means that you can do things like MyModel.findOne({}).then().catch() and await MyModel.findOne({}).exec() if you're using async/await.
Upon calling .exec() it executes your query and returns a promise that you can await in async function by doing so something like
Which would await the promise to be resolved and provide you with the result/handle error.
Using await without .exec() is also a valid approach, more information can be found at: Should You Use exec() With await?
Otherwise you can use the thenable approach, which would execute the query and provide you with the result in .then() .catch().
Example:
For better understanding, I would highly recommend checking out Mongoose Promises documentation page