Update the entry where _id =: id with Mongoose

I am trying to update an existing entry using Mongoose. The insert is OK, but not an update.

Here is my snippet:

app.post('/submit', function(req, res) { var my_visit = new models.visits({ date: req.body.visit_date, type: req.body.visit_type, agency: req.body.visit_agency, city: req.body.visit_city, url: req.body.visit_url, note: req.body.visit_note }); // INSERT if(req.body.id == 0) { my_visit.save(function(err) { if(err) { throw err; } console.log('added visit'); res.redirect('/'); }); } else { // UPDATE var upsertData = my_visit.toObject(); console.log(req.body.id); // OK models.visits.update({ _id: req.body.id }, upsertData, { multi: false }, function(err) { if(err) { throw err; } console.log('updated visit: '+ req.body.id); res.redirect('/'); }); } }) 

Answer Mod on _id is not allowed .

I just want to update a row like WHERE id = id in MySQL. I did not find the correct syntax.

+2
source share
1 answer

According to this question and this other , Mod on _id is not allowed occurs when you try to update an object based on its identifier without deleting it first.

I also found this github issue which is trying to explain the solution. It explicitly states:

Be careful not to use an existing instance of the model for the update clause (this will not work and may cause strange behavior such as infinite loops). Also, make sure the update clause does not have the _id property, which causes Mongo to return a "Mod on _id not allowed" error.

The solution seems to do the following:

 var upsertData = my_visit.toObject(); console.log(req.body.id); // OK delete upsertData._id; models.visits.update({ _id: req.body.id }, upsertData, { multi: false }, function(err) { if(err) { throw err; } //... } 

On the other hand, you can probably rewrite your route to create and update without an if-else clause. update () gets an additional upsert option, which, according to the docs:

upsert (boolean), whether to create a document if it does not match (false)

+10
source

Source: https://habr.com/ru/post/953670/


All Articles