Home > Software design >  mongoose.findByIdAndUpdate will only save the first key-value of object being pushed into array
mongoose.findByIdAndUpdate will only save the first key-value of object being pushed into array

Time:11-05

I have a simple object that stores two values inside, each being a req.body value from data sent from client.

const pushedVote = {
      answer: req.body.answer, 
      text: req.body.value
    }

Now, when I call the findByIdAndUpdate method it looks like this (with Poll being my model)

//insert answer and text 
    await Poll.findByIdAndUpdate(req.body.id, {
      $push: {
        responseAnswers: pushedVote,
      },
    });

This all works fine, but what's weird is that the array in my database that is updated will ONLY store the first key-value pair in the object. For example, if the pushedVote object that is being stored had answer as 'A' and text as 'Cat', the database will only store 'A', and not 'Cat' along with it. Am I missing something here?

CodePudding user response:

As per my comment, make sure that the text property is defined in the Mongoose schema, otherwise it won't be saved to the database.

  • Related