匹配mongoose populate中的特定值

问题描述 投票:1回答:2

以下是用户集合的架构:

const Mongoose = require('mongoose')

const Schema = Mongoose.Schema

const userSchema = new Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String
    },
    supporterOf: [{
        type: Schema.Types.ObjectId,
        ref: 'individual',
        required: false
    }],
})

module.exports = Mongoose.model('user', userSchema);

我想填充'supporterOf',这是个人(ref:个人)的集合。 'supporterOf'包含一个ObjectId数组。我遇到了将特定objectId与ObjectId数组匹配的问题。任何人都可以建议我如何在populate函数中将特定的ObjectId与ObjectId数组匹配?

node.js mongodb mongoose populate mongoose-populate
2个回答
1
投票

您在supporterOf中引用了“个人”,并且您希望仅填充个人数组中的相关对象?如果这是正确的情况,请执行以下操作:

YourUserModel.findById(userId, function (err, user) {
        console.log(user)
     }).populate({
        path: 'supporterOf',
        match: {
           yourObjectOfIndividualDocument: yourMatchingIdOfIndividual
        }
     })
     .exec()

yourObjectOfIndividualDocument: yourMatchingIdOfIndividual替换name: 'abcd'。这里name是个人文档的字段而不是用户文档。


0
投票

你在populate添加条件

如果你想根据他们的年龄填充粉丝阵列,并且最多返回其中任何5个

.populate('fans', null, { age: { $gte: 21 }}, { limit: 5 })
© www.soinside.com 2019 - 2024. All rights reserved.