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

青春壹個敷衍的年華 提交于 2019-12-21 10:18:09

问题


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!


回答1:


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.




回答2:


Article.findByIdAndUpdate(id, { $set: { day: 'example' }}, { new: true }, function (err, article) {
  if (err) return handleError(err);
  res.send(article);
});

I prefer this way because it's contains a callback function.

reference and more info: http://mongoosejs.com/docs/documents.html




回答3:


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


来源:https://stackoverflow.com/questions/23959287/add-a-field-to-existing-mongodb-document-with-mongoose-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!