Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving object with mongoose findOne / save doesn't work

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?

like image 222
Shamoon Avatar asked Mar 12 '23 23:03

Shamoon


1 Answers

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); 
    } 
})
like image 178
Kairat Avatar answered Mar 14 '23 13:03

Kairat