gpt4 book ai didi

node.js - 在 mongoose 中填充引用到其他字段而不是 _id,引用自定义字段而不是 _id

转载 作者:太空宇宙 更新时间:2023-11-04 01:40:56 32 4
gpt4 key购买 nike

    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 个模式,即用户、影响者、事件模式。用于填充的代码如下:

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

有人可以告诉裁判在事件模式中使用影响者字段吗?我想将该字段引用到影响者模式中的 user_id 而不是_id 字段,我不知道该怎么做。

最佳答案

您使用的填充错误。如果我理解正确的话,您实际上不想填充影响者,而是填充 InfluencerId。而不是

.populate("influencers")

使用

.populate({path: "influencers.influencerId"})

但是,这不会完全按照您想要的方式进行。因为它会解析为类似的内容

"influencers" : [
"status" : 0,
"influencerId" : {
//content of influencer
}
]

如果您想要您所说的结果,您需要随后映射数组。

关于node.js - 在 mongoose 中填充引用到其他字段而不是 _id,引用自定义字段而不是 _id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52995276/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com