如果可能的话,我如何以其他方式重命名mongoose中的返回字段?

时间:2017-08-22 13:57:45

标签: javascript mongodb

我有这个问题:

MessageModel.find({ conversationId: { $in: ids } })
            .sort({createdAt: 'ascending'})
            .populate({ path: 'receiver', select: '_id' })
            .populate({ path: 'sender', select: '_id' });

顾客和发件人会返回相同的ID字段吗?我想重命名_id等于相关的receiverId和senderId?

1 个答案:

答案 0 :(得分:1)

我建议使用$lookup而不是填充

MessageModel.aggregate({$match:{ conversationId: { $in: ids } }},
{$lookup: {
  from: 'receiver',
  localField:'receiver',
  foreignField: '_id',
  as: 'receiver'
}},
{$unwind:'$receiver'},
{$lookup: {
  from: 'sender',
  localField:'sender',
  foreignField: '_id',
  as: 'sender'
}},
{$unwind:'$sender'}

)