The returned Mongoose model cannot be updated

I am new to Mongoose / Mongo and node.js, so I suspect this is just a misunderstanding on my side, but ...

The following code example is the smallest unsuccessful example, not a specific use case.

var User = app.db.model('User'); User.find({email: ' m8@test.com '}, function (err, models) { models[0].update(function(err, mod) { console.log(err.message) }); }); 

This leads to the following error: After applying the update to the document {_id: ObjectId ('54647402cb955748153ea782'), ...}, it was found that the (immutable) field "_id" was changed to _id: ObjectId ('546d9e0e539ed9ec102348f9')

Why is this happening? I would have thought that it would be nice to cause an update to the model returned from the original find.

Please note: in my case there are things that happen between searching and updating. In particular, I am doing something similar to:

 model.property.push(objectId) 

Whom I want to accomplish with an update.

I am sure that this is a straightforward problem, but I do not see anywhere in the documents, I can be wrong.

All help was appreciated.

UPDATE:

I really needed to:

 var User = app.db.model('User'); User.find({email: ' m8@test.com '}, function (err, models) { models[0].save(function(err, mod) { console.log(err.message) }); }); 

Using 'save', not 'update'

+5
source share
1 answer

I don't know if I understood

Find and update (for example, using express)

 var email = req.params.email; User.find({email:email}, req.body, function(err,user){ if(err){ throw err; } //you do stuff like this var obj = { password:'new pass', username:'username' } //use save if you want validate User.update(user[0],obj,function(err, mod) { console.log(err) }); }); 

Update only: (e.g. using express)

 User.update({email:email}, req.body, {}, function(err,user){ if(err){ throw err; } res.send(200, { message : 'User updated ' + user }); }); 

Remember, that:

The model is a compiled version of the circuit.

Hope this helps you.

+4
source

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


All Articles