以下是用户集合的架构:
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数组匹配?
您在supporterOf中引用了“个人”,并且您希望仅填充个人数组中的相关对象?如果这是正确的情况,请执行以下操作:
YourUserModel.findById(userId, function (err, user) {
console.log(user)
}).populate({
path: 'supporterOf',
match: {
yourObjectOfIndividualDocument: yourMatchingIdOfIndividual
}
})
.exec()
用yourObjectOfIndividualDocument: yourMatchingIdOfIndividual
替换name: 'abcd'
。这里name
是个人文档的字段而不是用户文档。
你在populate添加条件
如果你想根据他们的年龄填充粉丝阵列,并且最多返回其中任何5个
.populate('fans', null, { age: { $gte: 21 }}, { limit: 5 })