User.find({ name: name}) 总是返回 null [关闭]

问题描述 投票:0回答:0

我正在尝试为我的项目创建一个个人资料页面。由于某种原因,我在查询 MongoDB/Mongoose 时无法找到我的用户配置文件。

这是我目前路线的代码(我的 isLoggedIn 和 asyncCatcher 函数可以正常工作):

router.get('/myprofile', isLoggedIn, asyncCatcher(async(req, res) => {
    const user = await User.findOne({name: req.user.username});
    console.log(req.user)
    console.log(user);
    res.render('profile/myprofile', { user });
}));

req.user 返回正确的信息,如下所示:

{
  _id: new ObjectId("64ee4407cc4a41033a32aa57"),
  email: '[email protected]',
  username: 'Name',
  __v: 0
}

当我尝试直接在 MongoDB 中搜索时,这是同样的问题:

db.users.find({name: 'Name'})
不返回任何内容

但是,当搜索像

db.users.find({})
这样的所有用户时,它会返回包含所有数据的完整列表。

当我对另一个集合进行类似搜索时,效果很好:

db.stuffs.find({name: 'TESTTEST'})
返回:

{
    _id: ObjectId("64f45b97c7f25353ef56f59a"),
    name: 'TESTTEST',
    category: 'asdasdasdasdasd',
    posts: [],
    author: ObjectId("64ef7a70af2dd6ad3c6c20ec"),
    __v: 0
  }

我唯一不确定的是 Passport,因为我用它来验证我的用户,但它对于登录等工作正常,这是我的 app.js 中的 Passport 代码:

app.use(passport.initialize());
app.use(passport.session());
passport.use(new LocalStrategy(User.authenticate()));

passport.serializeUser(User.serializeUser());
passport.deserializeUser(User.deserializeUser());

app.use((req, res, next) => {
    // console.log(req.session);
    res.locals.currentUser = req.user;
    res.locals.success = req.flash('success');
    res.locals.error = req.flash('error');
    next();
});

是否是护照以某种方式阻止了它?我最近才开始使用它,可能错过了它实际工作原理的一些东西。任何帮助表示赞赏。

javascript mongodb express mongoose passport.js
© www.soinside.com 2019 - 2024. All rights reserved.