在我调用子文档上的populate后,该子文档上的任何后续填充调用都会失败。
我定义了这些模式:
const MessageSchema = new Schema({
accountId: {type: ObjectId},
authorId: {type: ObjectId},
conversationId: {type: ObjectId},
body: {type: Object},
createdAt: {type: Date},
}, {
toObject: {
virtuals: true,
},
});
MessageSchema.virtual('author', {
ref: 'User',
localField: 'authorId',
foreignField: '_id',
justOne: true,
});
module.exports.Message = mongoose.model('Message', MessageSchema);
const Conversation = new Schema({
accountId: {type: String},
authorId: {type: ObjectId},
createdAt: {type: Date},
isArchived: {type: Boolean},
lastMessage: MessageSchema,
participants: [{type: Schema.Types.ObjectId, ref: 'User'}],
}, {
toObject: {
virtuals: true,
},
});
Conversation.virtual('account', {
ref: 'Account',
localField: 'accountId',
foreignField: '_id',
justOne: true,
});
module.exports.Conversation = mongoose.model('Conversation', Conversation);
我有一条运行此路线的路线:
const messages = await MessageModel.find({
conversationId: ObjectId(req.params.conversationId),
})
.populate('author')
.sort('+createdAt')
.skip(skip)
.limit(limit);
作为预期返回作者,但是,如果我运行以下内容,则对作者的任何后续调用都不会加载到作者中。
const conversation = await ConversationModel.findOne({
_id: ObjectId(req.params.conversationId),
})
.populate('participants')
.populate('lastMessage.author')
.populate('account')
.exec();
这是一个非常奇怪的,我无法弄清楚它为什么会发生。如果我删除.populate('lastMessage.author')
问题就会消失,但我需要填充它。