I'm doing a simple findOne() and saving the doc within it, but for some reason it's not working. I've outputted the object and the output in console is correct, but after the save(), I take a look at my mongodb and it didn't save. I'm not sure if there is some sort of option I'm supposed to set. Here is my code:
var1 = "data1";
var2 = "data1field1";
Model.findOne({'_id':some_id}).exec(function(err, doc) {
if (err) return console.error(err);
(doc.data[var1][var2][0] += 1;
console.log(doc.data.data1);
doc.save(function (err) {
if(err){console.log(err);}
console.log('success');
});
});
Here is my schema:
var modelSchema = new mongoose.Schema({
'data':{
'data1':{
'data1field1':[{type: Number}],
'data1field2':[{type: Number}]
},
'data2':{
'data2field1':[{type: Number}],
'data2field2':[{type: Number}]
}
}
});
var Model = mongoose.model('model', modelSchema);
module.exports.Model = Model;
Say I create an instance of this schema where data.data1.data1field1 is an array of two numbers [0,0], the output for "console.log(doc.data.data1);" would be:
{
data1field1:[1,0],
data1field2:[0,0] }
success
But the save does not happen. I'm new to mongoose/mongodb so there is probably a simple fundamental thing I'm missing.
NOTE: I cannot use Model.update({},{$inc {}}) because I'm using variables to select which data object to change, and because of the literals in .update(), it is impossible.
Thanks.
So mongoose has some smarts to automatically detect changes when you do simple property sets like myModel.name = 'Steve'
. However, when you access deeply nested schemas and change properties deep in the graph, the top level document cannot auto-detect this. So you need to tell mongoose what you changed.
doc.markModified('data.' + var1 + '.' + var2);
If you get the correct incantation of that, mongoose will be able to save your change.
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