猫鼬查找和更新嵌套文档

时间:2020-11-05 07:25:22

标签: mongodb mongoose

我正在尝试查找和更新另一个子文档下的一个子文档。我没有得到预期的结果。这是我目前已设置的:

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,
        },
    }
);

1 个答案:

答案 0 :(得分:2)

如果您没有onSubmit = () => {} functionsName : () => {} id,则必须从MongoDB 4.2开始使用update with aggregation pipeline

  • campaigns.campaign更新$set字段,campaigns更新$map数组循环,campaigns更新$map数组循环并检查如果campaigns.responses匹配,则返回updateFields,否则返回旧字段并使用responseId与当前对象合并
$mergeObjects

Playground


第二个选项,如果您具有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>]

Playground