简体   繁体   English

使用nodejs保存后如何从mongodb获取数据?

[英]How to get data from mongodb after saving it using nodejs?

My web application is like quiz app, the user should answer a question and the server will store the user's result in mongoDB database.我的 web 应用程序就像测验应用程序,用户应该回答一个问题,服务器会将用户的结果存储在 mongoDB 数据库中。 what I is want is after saving the document in the database I want to get this document to send it to user in the browser note saving documents works fine .我想要的是在将文档保存在数据库中之后,我想让这个文档在浏览器中发送给用户注意保存文档工作正常 code looks like this (assuming the user's result is 10):代码如下所示(假设用户的结果是 10):

    const User_Result = require("../models/result_model")
router.post("/quiz/results", (req, res)=>{
       var result = new User_Result({
            _id: req.user._id,
            userResult: 10
      })
      result.save()


     //that should get data and send it but it send empty []
     User_Result.find({_id: req.user._id}).then(data=>{
            res.send(data)
        })
})

I think the problem that it looks for the data before saving it.我认为它在保存数据之前查找数据的问题。

You don't need to use find as .save() will return the saved document you can just use it您不需要使用find因为.save()将返回保存的文档,您可以使用它

Async/Await version异步/等待版本

router.post("/quiz/results", async (req, res)=>{
       let result = new User_Result({
            _id: req.user._id,
            userResult: 10
      })
       const ReturnedResult = await result.save();
       return res.status(201).json(ReturnedResult);
})

Promise Version Promise版本

router.post("/quiz/results",  (req, res) => {
    let result = new User_Result({
      _id: req.user._id,
      userResult: 10
    })
    result.save()
      .then(ReturnedResult =>return res.status(201).json(ReturnedResult))
      .catch(err => return res.status(500).json(err))

  })

result.save() returns a promise, you should wait for it to be resolved: result.save() 返回一个 promise,你应该等待它被解决:

result.save().then(() => {
  User_Result.find({_id: req.user._id}).then(data=>{
    res.send(data)
  })
})
router.post("/quiz/results", async (req, res)=>{
       var result = new User_Result({
            _id: req.user._id,
            userResult: 10
      })
      const newResult = await result.save():
       return res.send(newResult).status(201);
})

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

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