0

I have something like a quiz app and the user should answer and see the result after submitting. I save the results in mongoDB database and I use foreach loop because it is more than one question and I want to send the result to user after saving the document note: saving document and replacing it works fine. my code looks like this:

//answers model
const User_Result = require("../models/result_model")

router.post("/quiz/results", (req, res)=>{
  var lastResult = 1;
  answersLenght.forEach((single, i) => {
        if(i==0) { //for the first right answer it should creat a document
          var result = new User_Result({
               id: req.user._id,
               endResult: lastResult
           })

           result.save()
        } else { // for other answers it should update endResult 
           lastResult = lastResult + 1
           User_Result.findOneAndReplace({_id: req.user._id}, {endResult: lastResult}, {new: true}, (err, r)=>{console.log(r)})
          }
  })
//it send empty []
  User_Result.find({_id: req.user._id}).then(data=>{
        res.send(data)
  })
})

it send empty [ ] because it looks for document before saving it

Akram Adil
  • 23
  • 4
  • Do you really need to do multiple mongodb requests at all? Can't you just merge the answer objects into an `endResult` first, and then store that in a single request? – Bergi Aug 11 '20 at 01:22
  • Can you explain more? – Akram Adil Aug 11 '20 at 11:49
  • It's really unclear what you're trying to do here and what the value of `answersLenght` is. Also, what `User_Result`s are you trying to find and/or update? It looks like you're repeatedly writing to the same mongo object. – Bergi Aug 11 '20 at 13:22

1 Answers1

0

You are saving a User_Result document with id:

var result = new User_Result({
           id: req.user._id,
           endResult: lastResult
       })

However, you're querying for User_Result documents using _id.

What you want to do is set _id to req.user._id like so:

//answers model
const User_Result = require("../models/result_model")

router.post("/quiz/results", (req, res)=>{
var lastResult = 1;
answersLenght.forEach((single, i) => {
    if(i==0) { //for the first right answer it should creat a document
      var result = new User_Result({
           _id: req.user._id,
           endResult: lastResult
       })

       result.save()
     } else { // for other answers it should update endResult 
        lastResult = lastResult + 1
        User_Result.findOneAndReplace({_id: req.user._id}, {endResult: lastResult}, {new: true}, (err, r)=>{console.log(r)})
      }
  })
  //it send empty []
  User_Result.find({_id: req.user._id}).then(data=>{
    res.send(data)
 })
})