【问题标题】:Mongoose/Nodejs - populate function only returns object id of userMongoose/Nodejs - 填充函数仅返回用户的对象 ID
【发布时间】:2018-11-23 08:02:28
【问题描述】:

目标:在引用模型中返回用户信息。

问题:我相信我的模型名称(缺乏约定)正在摆脱填充功能。我想返回我的用户名,但没有得到它。

这是我的用户模型:

const UserSchema = new Schema({
profile: {
    firstName: { type: String },
    lastName: { type: String }
  },
});
module.exports = mongoose.model('user', UserSchema, 'user');

还有我的物品型号:

const ItemSchema = new Schema({
user: {
    type: Schema.Types.ObjectId,
    ref: 'user',
  },
const PlayLoop = mongoose.model('items', ItemSchema);

在我的控制器中,我的函数如下所示:

show(req, res, next) {
    const id = req.params.id
    Items.findById({_id: id})
    .populate({
      path:'User',
    })
    .exec(function(err, item) {
      if (err) {console.log(err)}
      console.log(item)
    })

  },

返回的是我的物品模型:

{  _id: ITEM_ID,
  title: 'some title',
  user: USER_ID,
}

对于用户,我想返回完整的个人资料信息。 想法?

【问题讨论】:

  • Items.findById({_id: id}) .populate({ path:'user', }) 这里User 应该是user
  • 当我将我的函数更新为:.populate({ path:'user', }) 我的用户返回 null。

标签: mongodb mongoose populate mongoose-populate


【解决方案1】:

问题是客户端代码没有指向正确的数据库。

【讨论】:

    猜你喜欢
    • 2020-11-11
    • 2020-07-26
    • 2017-10-26
    • 2017-02-10
    • 2018-06-11
    • 2014-11-02
    • 2016-12-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多