在猫鼬中,您可以执行以下操作:
var questionSchema = new Schema({
comments: [{type: ObjectId, ref: 'Comment'}]
})
然后您可以填充它。
但是,有没有一种方法可以将不同集合的文档存储在同一数组中?就像是:
var questionSchema = new Schema({
commentsAndAnswers: [{type: ObjectId, ref: 'Comment'}, {type: ObjectId, ref: 'Answer'}]
})
显然这是行不通的,但是您明白我的意思了。
谢谢!
我可以为您的问题提出三种解决方案。
第一种解决方案是将ObjectID
不带ref
s的s存储到另一个集合中:
var questionSchema = new Schema({
comments: [ObjectId]
})
它将正常工作,但是您需要为每个查询指定要填充的模型:
Question.findOne().populate('comments', Answer).exec(next)
但是我不确定您是否可以同时comments
使用Comment
和Answer
模型进行填充。
另一种解决方案是comments
使用ref
s作为对象存储:
var questionSchema = new Schema({
comments: [{
comment: {type: ObjectId, ref: 'Comment'}
answer: {type: ObjectId, ref: 'Answer'}
}]
})
现在,您可以在单个查询中填充评论和答案:
Question.findOne().populate('comments.comment comments.answer').exec(next)
如果要在单个数组中查看它们,可以添加一个virtual:
questionSchema.virtual('comments_and_answers').get(function () {
return this.comments.map(function (c) {
return c.comment || c.answer
});
})
您可以使用toObject传递函数摆脱原始数组。
最后,您可以重新设计架构,以使用相同的猫鼬模型将评论和答案存储在单个集合中。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句