我有一个包含文章的文章组,模型看起来像这样
var ArticleGroup = new mongoose.Schema({
articles:[{type:mongoose.Schema.Types.ObjectId,ref:'Article'}]
})
var Article = new mongoose.Schema({
rates:[{
uid:String,
rate:Number //user's rate number to this article
}]
})
现在一个用户(让我们称他为JACK)想要对ArticleGroup执行查询,填充此组中的文章,选择提交的费率
通常我这样做
ArticleGroupModel
.findById(articleGroupId)
.populate('articles','rates')
.select('articles')
.exec((err, articleGroup) => {
if (err) return next(err)
//...
})
但现在我只想要JACK&#39> 如果一篇文章有JACK的评分,那就回复那篇文章
{
_id:"23jrf23orj89p3fwje4",
rates:[{
uid:"JACK's uid",
rate:"JACK's rate number"
}]
}
如果一篇文章没有JACK的费率,那么文章仍然会被填充,但是这样的文章是空的
{
_id:"23jrf23orj89p3fwje4",
rates:[]
}
有没有办法做到这一点?
答案 0 :(得分:0)
为了获得这个结果,你应该重新考虑你的数据模型:
ArticleGroup = new mongoose.Schema
some details here ...
ArticleRate = new mongoose.Schema
uid: String
rate: Number
Article = new mongoose.Schema
group:
type: mongoose.Schema.ObjectId
ref: 'ArticleGroup'
rates:[ArticleRate]
执行此类查询:
Article
.find(group: groupId)
.populate({
path: 'rates',
match: { uid: { $in: { JACK_UID } } },
select: 'rate'
})
.exec();
您可以在Mongoose documentation中找到更多有用的信息。