Reputation: 43501
My model is:
GigSchema = new Schema({
lastUpdate: {
type: Date,
"default": null
},
type: {
type: String,
"default": null,
"enum": [null, 'mvp', 'code-review', 'extension', 'existent-code-review', 'internal', 'design']
},
meta: {
type: Object,
"default": {
chats: 0,
phoneCalls: 0,
responseTime: null
}
},
engaged: {
type: Date,
"default": null
}
});
And when I do:
Gig.findOne({
_id: data.gig
}).populate(populate).exec(function(err, gig) {
gig.meta.chats += 1;
return gig.save(function(err) {
return console.log(err);
});
});
I'm trying to update the meta
field, but it doesn't actually save, but also no error. What am I doing wrong?
Upvotes: 4
Views: 3111
Reputation: 800
Populate
should be used to get the references to documents in other collections. See http://mongoosejs.com/docs/populate.html
If you just want to update field in a document you can do the following:
Gig.findOne({_id: data.gig}, function (err, gig) {
gig.meta.chats += 1;
gig.save(function(err){
console.log(err);
})
})
Or you can also use Model.findOneAndUpdate
Gig.findOneAndUpdate({_id: data.gig}, { $inc: { meta.chats : 1 }}, {new: true}, function(err, doc){
if (err){
console.log(err);
}
})
Upvotes: 3
Reputation: 43501
So the answer has to do with using gig.markModified('meta')
since I'm modifying the properties of an object.
Upvotes: 3
Reputation: 84
use this structure... you have a problem with error catching and use update method if you want to update somethig, not save.
Gig.findOne({
_id: data.gig
}, function(err, gig){
if(err){
throw err;
}else if(gig){
Gig.update({_id: data.gig},{
meta.chats : gig.meta.chats + 1;
},
{
runValidators: true
},
function(err){
if(err) throw err;
}
);
});
hope this helps you. i am wait a result, think its be ok.
Upvotes: 2