Reputation: 178
I'm trying to update all the documents in my collection with new field I declare in my model. this field is boolean with default value of false.
I know this question is already asked before but still can't get solution for my problem.
everything I try not working.
here for examples for what i tried: update method that has empty query -cause I want to update all documents, and empty $set because I don't want to do any change, just add the field I added in my model
User.update({},{},{multi: true},function(err,num) {
if (err){
console.log(err);
}
console.log(num);
console.log("all documents were updated with new field)
})
another try :
User.find({},function (err,docs) {
async.each(docs,function (doc,cb) {
doc.save(function (err) {
console.log(err);
cb();
})
},function () {
console.log("all documents were saved with new field)
})
})
any suggestions?
Upvotes: 0
Views: 4275
Reputation: 11330
Mongoose does not allow to set undefined
values to fields. Those fields are absent from the document. You need to pass something to Mongoose to set as the value of that new field.
So you could set an empty String -
User.update({},{$set: {newField: ''}}......)
or null -
User.update({},{$set: {newField: null}}.....)
but you need to provide some values in order for Mongoose to set it to the documents.
Edit -
From the mongoose documentation -
By default, mongoose only applies defaults when you create a new document. It will not set defaults if you use update() and findOneAndUpdate(). However, mongoose 4.x lets you opt-in to this behavior using the setDefaultsOnInsert option.
You can read more about it here.
Upvotes: 2