0

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. 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):

    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.

3 Answers 3

2

You don't need to use find as .save() will return the saved document you can just use it

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

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))

  })
Sign up to request clarification or add additional context in comments.

1 Comment

your answers are very helpful but now I update the question, so can you help?
1

result.save() returns a promise, you should wait for it to be resolved:

result.save().then(() => {
  User_Result.find({_id: req.user._id}).then(data=>{
    res.send(data)
  })
})

Comments

1
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);
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.