无法访问mongoose populate中的属性?

时间:2017-08-20 20:28:27

标签: javascript mongodb mongoose

我的消息架构:

const MessageSchema = new Schema({  
  conversationId: {
    type: Schema.Types.ObjectId,
    required: true
  },
  body: {
    type: String,
    required: true
  },
  seen: {
    type: Boolean,
    default: false,
  },
  sender: {
    type: Schema.Types.ObjectId,
    ref: 'userModel' 
  },
  receiver: {
    type: Schema.Types.ObjectId,
    ref: 'userModel' 
  },
},
{
  timestamps: true 
});

当我在console.log接收者和用户时,它返回一个对象,就像这样:

 { _id: 597f7eb1e5131d5a50e18d14,
     updatedAt: 2017-07-31T19:02:09.035Z,
     createdAt: 2017-07-31T19:02:09.035Z,
     fullName: 'ria atayde',
     email: 'myloves@gmail.com',
     password: '$2a$08$Kbkk69.8I9RQvTaRXy3nw.Oj.SEPhKPmhtI/ZWxIHyz2lgYiciVlC',
     todos:
      [ 597f801eab95955c1469bbfc,
        597f8026ab95955c1469bbfd,
        597f8030ab95955c1469bbfe ],
     friendsIds: [ '597f7e3ce5131d5a50e18d13' ],
     active: true,
     __v: 0 }

这是我的疑问:

await MessageModel.find({ conversationId: { $in: conversationIdsByUser } })
                                      .populate({path:'receiver' ,options: { lean: true}})
                                      .populate({path:'sender' ,options: { lean: true}})
                                      .lean();

我已经使用了精益,但仍无法访问接收方和发送方属性,例如receiver._id?但对象在那里?

1 个答案:

答案 0 :(得分:0)

这有用吗?

await MessageModel.find({ conversationId: { $in: conversationIdsByUser } })
  .populate('receiver sender', { lean: true}})
  .lean();

当您尝试在没有lean选项的情况下进行查询时会发生什么?

await MessageModel.find({ conversationId: { $in: conversationIdsByUser } })
  .populate('receiver sender');

你也应该尝试上面的内容,因为有人在mongoose GitHub上评论说使用精简版和填充符是still buggy