How to update a record?

I am writing a basic application with an Express / NodeJs backend that relies on mongoDb (via mongoose) for storage.

It's time to update the records in the database, and I click on the wall.

Code I wrote: https://gist.github.com/b90130f640cea75b0cbd

I understand that the error preventing the upgrade is due to the fact that I pass all the fields, including the unchangeable "_id".

I ask: is there a way to pass all the fields to the update method or do this? should indicate them one by one (or iterate over them all)?

Thanks in advance for your help, hello.

+4
source share
2 answers

you can remove _id before passing it to model.update()

+2
source

You can just upgrade instead of updating.

 new User(req.body).save(); 

In any case, except that req.body will have the correct data, there may be security problems depending on how your models are (GitHub has had such a problem lately).

My advice is to get only what you want from req.body and update.

 var updateData = { name: req.body.name }; User.update({_id: user._id},updateData, function(err,affected) { console.log('affected rows %d', affected); }); 
+2
source

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


All Articles