我正在尝试查找和更新另一个子文档下的一个子文档。我没有得到预期的结果。这是我目前已设置的:
const SiteSchema = new mongoose.Schema({
domain: { type: String, required: true },
keywords: [],
campaigns: [
{
campaign: {
type: mongoose.Schema.Types.ObjectId,
ref: "Campaign",
},
responses: [
{
message: { type: String },
asking_fee: { type: Number },
date: { type: Date },
},
],
}],
})
我想查找和编辑特定回复。这是我现在的代码。我是猫鼬和MongoDB的新手。
const site = await Site.findOneAndUpdate({
"campaigns.responses._id": responseId, // will it fetch the response ?
}, {
$set: { // I am struggling with the following
"campaigns.$.responses.message": message,
"campaigns.$.responses.asking_price": asking_price,
"campaigns.$.responses.date": date,
},
}
);
答案 0 :(得分:2)
如果您没有onSubmit = () => {}
functionsName : () => {}
id,则必须从MongoDB 4.2开始使用update with aggregation pipeline,
campaigns.campaign
更新$set
字段,campaigns
更新$map
数组循环,campaigns
更新$map
数组循环并检查如果campaigns.responses
匹配,则返回updateFields,否则返回旧字段并使用responseId
与当前对象合并$mergeObjects
第二个选项,如果您具有let responseId = 1;
let updateFields = {
message: "new message",
asking_fee: 10,
date: new Date()
};
const site = await Site.findOneAndUpdate(
{ "campaigns.responses._id": responseId },
[{
$set: {
campaigns: {
$map: {
input: "$campaigns",
in: {
$mergeObjects: [
"$$this",
{
responses: {
$map: {
input: "$$this.responses",
in: {
$mergeObjects: [
"$$this",
{
$cond: [
{ $eq: ["$$this._id", responseId] },
updateFields,
"$$this"
]
}
]
}
}
}
}
]
}
}
}
}
}]
)
id,则可以使用campaigns.campaign
arrayFilters,
$[<identifier>]