I'm trying to update a particular subfield in a mongoDB document and have decided to first find the object in question and then save an updated one. For some reason, the save option seems to ignore my changes.
I have one object in my collection, and it meets the following schema:
var tschema= mongoose.Schema({
a: Object
})
var t = db.model('tongoose',tschema);
t.findOne({},function(err,obj){
console.log(obj.a); //yields ['banana',3]
obj.a[1]=1; //to make ['banana',1]
console.log(obj); //yields ['banana',1]
obj.save(function(err,real){
console.log(real); //yields ['banana',1]
});
});
But when I go back to the mongoDB and look up the saved object, it never shows any changes. Can you spot what I'm doing wrong?
Much appreciated.
Because your schema defines a
as a generic object, that field is treated as the Mixed
type by Mongoose and you need to mark it as changed by calling markModified
or save
will ignore the change.
obj.markModified('a');
obj.save(function(err,real){ ...
See the discussion of Mixed
types on this page of the docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With