Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (50.2k points)

I'm using mongoose 4.0.7. Compare the following two command:

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

    ...

    })


 

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

    ...

    })

And this is my WorkPlan schema:

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

And the following is my updateObj:

    var updateObj = {

        projectManagerName: projectManagerName,

        clientEmail: clientEmail,

        clientPhoneNumber: clientPhoneNumber,

        segmentationsToDisplay: segmentationsToDisplay ? segmentationsToDisplay.split(',') : []

    }

While the project is being created, the outcome of the first command is the same as the result of the second command that means that my updateObj gets mixed into the existing record in the MongoDB database. How can I replace an object on an update rather than merging it? 

1 Answer

0 votes
by (108k points)

You have to add a parameter that is 'overwrite' and set that argument as true. Refer to the following code:

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

    ...

})

In your provided code, all the top-level operations are being treated as a $set operation in MongoDB that is why you are getting the same outcomes. 

Related questions

0 votes
1 answer
0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Mar 14, 2020 in Web Technology by ashely (50.2k points)

Browse Categories

...