Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a field to existing MongoDB document (with Mongoose in Node.js)

I have this existing document in a collection Article in MongoDB database:

[ { site: 'www.atlantico.fr',
date: '2014-05-27T11:10:19.000Z',
link: 'http://www.atlantico.fr/example.html',
_id: 538473817eb00f082f4803fc,
__v: 0} ]

I want to add a new field day with value 'example' to this document, using Mongoose in Node.js. So I do:

Article.update(
      { link: 'http://www.atlantico.fr/example.html'}, 
      { $set : {day : 'example'} }, 
       function(err){  
                    });

But it does not work because when I query the document after that, no new field day appears...

I must have made a mistake when using update or $set in Mongoose, but I cannot find exactly my mistake.

What am I missing? Thanks!

like image 927
GBC Avatar asked May 30 '14 16:05

GBC


2 Answers

await Users.updateOne( {link: 'http://www.atlantico.fr/example.html'},{ $set: { day : 'example'} }, { multi: true });
  • update is deprecated
  • use await for db operation
  • if you want to add new filed in collection ,first check it is added in Model or not (if you don't wan't use that filed as mandatory make is as "required: false")
like image 134
Bhagvat Lande Avatar answered Oct 09 '22 19:10

Bhagvat Lande


try

Article.update(
     {link: 'http://www.atlantico.fr/example.html'}, 
     {day : 'example' },
     {multi:true}, 
       function(err, numberAffected){  
       });

and don't forget to add day to schema.

like image 21
Sergey Zhukov Avatar answered Oct 09 '22 19:10

Sergey Zhukov