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: '',
date: '2014-05-27T11:10:19.000Z',
link: '',
_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:

      { link: ''}, 
      { $set : {day : 'example'} }, 

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!

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1


     {link: ''}, 
     {day : 'example' },
       function(err, numberAffected){  

and don’t forget to add day to schema.

Solution 2

await Users.updateOne( {link: ''},{ $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”)

Solution 3

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

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

reference and more info:

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from or, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply