简体   繁体   English

猫鼬用数组元素的条件填充嵌套数组

[英]mongoose populate nested array with condition for array element

I have an ArticleGroup which contains articles, models look like this 我有一个ArticleGroup,其中包含文章,模型如下所示

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
    }]
})

now A USER (let's call him JACK) want to perform a query to ArticleGroup, populating articles in this group, selecting the rates filed 现在, 一个用户(我们称其为“杰克”)想要对ArticleGroup进行查询,以填充该组中的文章,并选择提交的费率

usually I do this 通常我这样做

ArticleGroupModel
    .findById(articleGroupId)
    .populate('articles','rates')
    .select('articles')
    .exec((err, articleGroup) => {
         if (err) return next(err)
         //...
    })

but now I ONLY want JACK's rate if one article has JACK's rate, just return that article like this 但是现在,如果一篇文章具有杰克的汇率,我现在只想要杰克的汇率,就可以像这样返回该文章

{
    _id:"23jrf23orj89p3fwje4",
    rates:[{
        uid:"JACK's uid",
        rate:"JACK's rate number"
    }]
}

if one article has no JACK's rate, the article is still populated, but with an empty rates filed like this 如果一篇文章没有“杰克”汇率,则仍会填充该文章,但会以这样的方式填写空汇率

{
     _id:"23jrf23orj89p3fwje4",
     rates:[]
}

Is there any way to do this? 有什么办法吗?

In order to obtain this result you should reconsider your data model with something like this: 为了获得此结果,您应该使用以下内容重新考虑您的数据模型:

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]

And perform this kind of query: 并执行这种查询:

Article
.find(group: groupId)
.populate({
   path: 'rates',
   match: { uid: { $in: { JACK_UID } } },
   select: 'rate'
 })
 .exec();

You could find more helpful informations within the Mongoose documentation . 您可以在Mongoose文档中找到更多有用的信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM