简体   繁体   English

findOneAndUpdate mongoDB 没有正确返回

[英]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这是我的 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这是 axios 调用

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

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. findOneAndUpdate(filter, update, options, callback)有一个returnOriginal选项,如果设置为true (这是默认值),它将在更新之前返回文档。 In your case, you might want to set it to false [1].在您的情况下,您可能希望将其设置为false [1]。

Unfortunately, the respective option for mongoose is named new [2].不幸的是,mongoose 的相应选项被命名为new [2]。

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

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

you need to change user schema, in that you might have defined choices type as string.您需要更改用户架构,因为您可能已将选择类型定义为字符串。 It must be an array.它必须是一个数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM