考虑以下命令:
WorkPlan.findOneAndUpdate({ _id: req.params.id }, updateObj, function(err) {
...
})
与此相比:
WorkPlan.findOneAndUpdate({ _id: req.params.id }, { '$set': updateObj }, function(err) {
...
})
在开发我的项目时,我惊讶地发现第一个命令的结果与第二个命令的结果相同:即使在第一种情况下,
updateObj
应该替换现有记录,它也会合并到数据库中的现有记录中。这是 mongoose/mongodb 的 bug 还是我的操作有误?我如何在更新时替换对象而不是将其合并?我使用的是 mongoose 4.0.7。谢谢。
==========
更新:
这是实际的 WorkPlan 架构定义:
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
不会存在于新记录中,但是我发现它仍然存在。