Reputation: 23
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.
Upvotes: 0
Views: 177
Reputation: 3642
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))
})
Upvotes: 2
Reputation: 357
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);
})
Upvotes: 1
Reputation: 340
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)
})
})
Upvotes: 1