首页 > 解决方案 > 无法从关联模型中检索数据

问题描述

我有一个用户模型和一个配置文件模型。

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const UserSchema = new Schema({
  name: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true
  },
  password: {
    type: String,
    required: true
  }
});

module.exports = User = mongoose.model('users', UserSchema);

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const ProfileSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: 'users'
  },
  handle: {
    type: String,
    required: true
  },
  bio: {
    type: String,
    required: true
  },
  location: {
    type: String,
    required: true
  }
});

module.exports = Profile = mongoose.model('profile', ProfileSchema);

我正在尝试在以下路线中检索用户名和电子邮件:

router.get('/', passport.authenticate('jwt', { session: false} ), (req, res) => {
  console.log(req.user);
  Profile.findOne({ user: req.user.id })
    .populate('user', ['name', 'email'])
    .then(profile => {
      if (!profile) {
        return res.status(404).json({error: 'Profile not found!'})
      }

      res.json(profile);
    })
    .catch(err => res.status(404).json(err));
});

即使用户存在于我的数据库中,我也会不断返回“找不到配置文件”。我也知道 id 正在传递,因为 console.log(req.user) 记录以下内容:

[0] Listening on port 8080!
[0] MongoDB connected
[0] { _id: 5afcab77c4b9a9030eee35a7,
[0]   name: 'Harry',
[0]   email: 'harry@gmail.com',
[0]   password: '$2a$10$vOkK/Mpx04cR06Pon0t.2u5iKqGXetGuajKTZyBvLNWwgPjN6RO3q',
[0]   __v: 0 }

将 req.user.id 传递给 Profile.findOne 应该检索配置文件以及相关的用户名和电子邮件,但我无法取回任何东西。任何帮助将不胜感激,谢谢!

这是出现在数据库中的 Profile 文档:

{
    "_id": {
        "$oid": "5b0715288ae56b028b442e7b"
    },
    "handle": "johndoe",
    "bio": "Hi, my name is John and I live in Toronto, ON, Canada!",
    "location": "Toronto, ON",
    "__v": 0
}

标签: javascriptnode.jsmongodbmongoose

解决方案


推荐阅读