猫鼬 - 找到一个和更新与$set旗帜



请考虑以下命令:

    WorkPlan.findOneAndUpdate({ _id: req.params.id }, updateObj, function(err) {
    ...
    })

与此相比:

    WorkPlan.findOneAndUpdate({ _id: req.params.id }, { '$set': updateObj }, function(err) {
    ...
    })

在开发我的项目时,我惊讶地发现第一个命令的结果与第二个命令的结果相同:updateObj被合并到数据库中的现有记录中,即使在第一种情况下它应该替换它。这是猫鼬/mongodb 中的错误还是我做错了什么?如何在更新时替换对象而不是合并它?我正在使用猫鼬 4.0.7。

谢谢。

========

==

更新:

这是实际的工作计划架构定义:

workPlanSchema = mongoose.Schema({
    planId: { type: String, required: true },
    projectName: { type: String, required: true },
    projectNumber: { type: String, required: false },
    projectManagerName: { type: String, required: true },
    clientPhoneNumber: { type: String, required: false },
    clientEmail: { type: String, required: true },
    projectEndShowDate: { type: Date, required: true },
    segmentationsToDisplay: { type: [String], required: false },
    areas: [
        {
          fatherArea: { type: mongoose.Schema.ObjectId, ref: 'Area' },
          childAreas: [{ childId : { type: mongoose.Schema.ObjectId, ref:   'Area' }, status: { type: String, default: 'none' } }]
        }
],
    logoPositions: [
                 {
                   lat: { type: Number, required: true },
                   lng: { type: Number, required: true }
                 }
    ],
    logoPath: { type: String, required: false },
    }, { collection: 'workPlans' });

WorkPlan = mongoose.model('WorkPlan', workPlanSchema);

这是updateObj的一个例子:

    var updateObj = {
        projectManagerName: projectManagerName,
        clientEmail: clientEmail,
        clientPhoneNumber: clientPhoneNumber,
        segmentationsToDisplay: segmentationsToDisplay ? segmentationsToDisplay.split(',') : []
    }

因此,当我不使用 $set 标志时,我希望字段projectNumber ,例如,在新记录中不存在,但我看到它仍然存在。

Mongoose 更新将所有顶级键视为$set操作(这在较旧的文档中更明确:Mongoose 2.7.x 更新文档)。

为了获得所需的行为,您需要将overwrite选项设置为 true:

WorkPlan.findOneAndUpdate({ _id: req.params.id }, updateObj, { overwrite: true }, function(err) {
    ...
})

请参阅猫鼬更新文档

除了上面的答案:

[选项.overwrite=false] «布尔值» 默认情况下,如果您不包含 文档中的任何更新运算符,猫鼬都会为您包装$set文档中。 这可以防止您意外覆盖文档。这 选项告诉猫鼬跳过添加$set。

链接到文档:https://mongoosejs.com/docs/api.html#model_Model.update

这对我来说$set在猫鼬5.10.1中工作,

 WorkPlan.where({ _id: req.params.id }).updateOne(updateObj);

注意:如果您有内部对象,请在updateObj中给出每个键的确切路径

例:

"Document.data.age" = 19

参考: https://mongoosejs.com/docs/api.html#query_Query-set

最新更新