为什么这个 Mongoose 查询返回预期结果,但我无法利用它的属性?

发布于 2025-01-11 03:10:23 字数 1513 浏览 3 评论 0原文

我想检查请求的文章页面是否实际上是经过 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

咆哮 2025-01-18 03:10:23

使用 .exec() 会触发查询并返回一个可用的 Promise,在 .exec() 中添加回调并不是等待 Promise 得到解析的有效方法 Mongoose 文档 它用于

[callback] «Function» 可选参数取决于函数
称为

Mongoose 异步操作,如 .save() 和查询,返回thenables。
这意味着如果您使用 async/await,您可以执行诸如 MyModel.findOne({}).then().catch() 和 wait MyModel.findOne({}).exec() 之类的操作。

调用 .exec() 后,它会执行您的查询并返回一个 Promise,您可以在异步函数中等待,方法是执行类似

    try{
       const res = await MyModel.findOne({}).exec()
    }catch(err){
       console.log(err)
       //err handling here
    }

Which 会等待 Promise 得到解决并为您提供结果/处理错误的操作。
使用await而不使用.exec()也是一种有效的方法,更多信息可以在以下位置找到:应该将 exec() 与 wait 一起使用吗?

否则,您可以使用 thenable 方法,该方法将执行查询并在 .then() 中为您提供结果.catch()。
示例:

Band.findOne({name: "Guns N' Roses"}).then(function(doc) {
  // use doc
}).catch(function(err){ console.log(err) });

为了更好地理解,我强烈建议查看 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

[callback] «Function» optional params depend on the function being
called

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

    try{
       const res = await MyModel.findOne({}).exec()
    }catch(err){
       console.log(err)
       //err handling here
    }

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:

Band.findOne({name: "Guns N' Roses"}).then(function(doc) {
  // use doc
}).catch(function(err){ console.log(err) });

For better understanding, I would highly recommend checking out Mongoose Promises documentation page

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文