I am trying to add a new field to a document, but this isn’t working:
Creating my UserModel prototype:
JavaScript
x
11
11
1
model = require("../models/user")
2
UserModel.prototype.findOneAndUpdate = function(query, params, cb) {
3
model.findOneAndUpdate(query, params, { returnNewDocument: true, new: true }, function(err, data) {
4
if (!err) {
5
cb(false, data);
6
} else {
7
cb(err, false);
8
}
9
});
10
};
11
Then calling it
JavaScript
1
13
13
1
userFunc = require("../../model_functions/user")
2
3
userFunc.findOneAndUpdate({
4
"email.value": userEmail
5
}, {
6
$set: {"wat":"tf"}
7
},
8
function (err, updatedUser) {
9
//This logs the updated user just fine, but the new field is missing
10
console.log(updatedUser);
11
12
});
13
This successfully updates any field as long as it exists, but it won’t add any new one.
Advertisement
Answer
You can add and remove fields in schema using option { strict: false }
option: strict
The strict option, (enabled by default), ensures that values passed to our model constructor that were not specified in our schema do not get saved to the db.
JavaScript
1
2
1
var thingSchema = new Schema({..}, { strict: false });
2
And also you can do this in update query as well
JavaScript
1
10
10
1
Model.findOneAndUpdate(
2
query, //filter
3
update, //data to update
4
{ //options
5
returnNewDocument: true,
6
new: true,
7
strict: false
8
}
9
)
10
You can check the documentations here