Jack Franklin
Jack Franklin

Reputation: 105

findOneAndUpdate mongoDB not returning properly

I am trying to push a user's choice as a string to their array of choices and return the updated document.

The route and function work successfully however it returns the User with an empty choice array. I believe the problem lies somewhere in the controller function but I cannot figure it out. Any help is greatly appreciated!

To help, here is a screenshot of my console where you can see an empty choice array being returned. Here is an image of my console.log


This is where I call the function

 handleAnswerInput = (question) => {
    let answerTextSelected = question.Text;
    let answerTypeSelected = question.Type;
    let usersName = this.state.user._id
    this.setState({
        count: this.state.count + 1
    })
    saveUserandScore(usersName, answerTextSelected)
        .then(
            this.loadQuestion(this.state.count)

        )
    console.log(answerTextSelected)
    console.log(answerTypeSelected)
};

This is the controller function (updated from suggestions)

const saveUserAndTheirScore = (req, res) => {
  let filter = { _id: req.params.id }
  // let update = { choices: req.params.answer] }
  console.log(req.params.id)
  console.log(req.params.answer)
  User.update(
    { filter },
    {
      $push: { choices: req.params.answer }
    },
    {
      returnOriginal: false,
    },
  )
    .then(dbData => res.json(dbData))
    .catch(err => {
      console.log(err);
      res.json(err);
    });
};

here is the axios call

    export const saveUserandScore = (id, answer) => {
  return axios.post(`/api/user/${id}/${answer}`);
};

Upvotes: 1

Views: 85

Answers (2)

pintxo
pintxo

Reputation: 2155

findOneAndUpdate(filter, update, options, callback) has a returnOriginal option, if set to true (which is the default), it will return the document BEFORE the update. In your case, you might want to set it to false [1].

Unfortunately, the respective option for mongoose is named new [2].

[1] https://mongodb.github.io/node-mongodb-native/3.4/api/Collection.html#findOneAndUpdate

[2] https://mongoosejs.com/docs/api.html#query_Query-findOneAndUpdate

Upvotes: 1

Alok Deshwal
Alok Deshwal

Reputation: 1126

you need to change user schema, in that you might have defined choices type as string. It must be an array.

Upvotes: 1

Related Questions