0

I'm trying to update a field in my nested array to change the "phone" number. Below is my function:

module.exports.checkIn = async(req, res) => {
    const idNum = req.body.guest;
    Event.findOneAndUpdate({"_id": req.params.id, "guests._id": idNum }, {phone: 22222 }, (error, data) => {
        if(error){
            res.send(error);
        } else {
            res.send(data);
        }
    });
}

For context, req.body.guest = 1234objectidnumberwithoutquotes5678

Here is my Event model:

const eventSchema = new Schema({
  address: String,
  description: String,
  guests: [
    {
      phone: Number,
      attended: String
    }
  ],
});

I'm not getting any errors but the phone number isn't updating. What am I missing? Have been combing through the mongoose docs and youtube and can't figure it out.

econobro
  • 315
  • 3
  • 17

1 Answers1

0
Model.findOneAndUpdate(conditions, update, options, (error, doc) => {
// error: any errors that occurred
// doc: the document before updates are applied if `new: false`, or after updates if `new = true`
}); 

You should use the third parameters which is option and pass new=true to get the return value as the updated value

Konflex
  • 465
  • 3
  • 11
  • I'm using my terminal to look at the database but I saw this in the mongoose docs. Not an issue with returning the newest value but an issue with the actual function -- that's where I'm looking for help. – econobro Nov 16 '21 at 17:10
  • The third parameter is missing in your function that why it isn't updated – Konflex Nov 16 '21 at 17:15
  • From what I can tell, I have a condition, update and a callback, which should execute based on the mongoose docs, no? From docs: A.findOneAndUpdate(conditions, update, callback) // executes . What am I missing here? https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate – econobro Nov 16 '21 at 18:11
  • 1
    The problem comes from the nested object in the array, check this out: https://stackoverflow.com/questions/56527121/findoneandupdate-nested-object-in-array – Konflex Nov 16 '21 at 18:17
  • that worked! Thanks for realizing where I was stuck - much appreciated!! – econobro Nov 17 '21 at 14:16