无法从关联模型中检索数据

时间:2018-05-25 18:24:46

标签: javascript node.js mongodb mongoose

我有用户模型和个人资料模型。

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应检索配置文件以及关联的用户名和电子邮件,但我无法获得任何回复。非常感谢任何帮助,谢谢!

这是出现在数据库中的个人资料文档:

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

0 个答案:

没有答案