userSchema={
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
role: {
type: String
}
}
influencerSchema={
user_id: {
type: Schema.Types.ObjectId,
ref: 'users'
},
profile: {
firstname: {
type: String
},
lastname: {
type: String,
default: null
},
mob: {
type: String,
default: null
},
email: {
type: String,
default: null
},
dob: {
type: Date,
default: null
},
gender: {
type: String,
default: null
}
}
}
campaign_schema={
CampaignName: {
type: String,
required: true
},
Brandcreated: {
type: Schema.Types.ObjectId,
required: true
},
status: {
type: Number,
default: 0
},
influencers: [{
influencerId: {
type: Schema.Types.ObjectId,
ref:"influencer"
},
status: {
type: Number,
default: 0
}
}]
}
以上是3个架构,即User,影响者,Campaign架构。 下面是用于填充的代码:
function(body) {
return new Promise(function(resolve, reject) {
campaign.find({
"_id": body.campaignId
}).populate('influencer')
.exec(function(err, doc) {
console.log(err);
if (err) {
reject();
} else {
resolve(doc);
}
});
});
}
上述功能给出的结果是
[
{
"status": 0,
"_id": "5bc4a9bf0c67a642d74ab6d1",
"influencers": [
{
"status": 0,
"_id": "5bccc0052db612466d8f26fb",
"influencerId": "5bbef7cd8c43aa1c4e9a09b5"
}
],
"CampaignName": "testCampaign",
"Brandcreated": "5bbf7857a7a55d30426cde37",
"__v": 0
}
]
和预期结果
[
{
"status": 0,
"_id": "5bc4a9bf0c67a642d74ab6d1",
"influencers": [
{
"status": 0,
"_id": "5bccc0052db612466d8f26fb",
"influencerId": "5bbef7cd8c43aa1c4e9a09b5"
user_id: {}
profile:{}
}
],
"CampaignName": "testCampaign",
"Brandcreated": "5bbf7857a7a55d30426cde37",
"__v": 0
}
]
有人可以告诉ref使用竞选模式中的“ influencers”字段,我想将该字段引用为影响者Schema中的user_id而不是“ _id”字段,我不怎么做。
答案 0 :(得分:0)
您使用的填充错误。您实际上并不希望填充影响者,但是如果我理解正确的话,那么不要影响者ID。代替
.populate("influencers")
使用
.populate({path: "influencers.influencerId"})
但是,这并不能完全显示您想要的方式。因为它将解析为类似的
"influencers" : [
"status" : 0,
"influencerId" : {
//content of influencer
}
]
如果您希望获得所声明的结果,则需要在以后映射数组。