user4392743
user4392743

Reputation:

Mongoose ODM findOneAndUpdate sub-document

I currently have a Message schema which has a sub-document of replies as such:

message: String,
replies: [{
   message: String,
   userFrom: {
      type: mongoose.Schema.Types.ObjectId,
      ref: 'User'
   }
 }]

I am attempting to make a POST request that will allow me to findOneAndUpdate the message to attach a reply. I've attempted the following:

Message.findOneAndUpdate(req.params.id,{
  replies: {
    message: req.body.reply,
    userFrom: req.user._id
  }
}, function(err, data){
  ...
});

What is happening is I am overwriting any reply that is currently in the replies array. I believe I need to use the $push operator but I'm not quite sure how.

Is it possible to use findOneAndUpdate as well as $push in a single request?

Upvotes: 3

Views: 7527

Answers (1)

chridam
chridam

Reputation: 103425

You were in the right direction. Using the following syntax

query.findOneAndUpdate(id, update, callback) // executes

you can do your update with the $push operator as follows:

var reply = {
    message: req.body.reply, 
    userFrom: req.user._id
};

Message.findOneAndUpdate(
    req.params.id,
    { $push: { replies: reply } },
    { upsert: true }, // upsert looks to find a Message with that id and if it doesn't exist creates the Message 
    function(err, data) {
        // Handle err
});

Upvotes: 8

Related Questions