how are you? I'm quite new to mongoose and mongoDB and I'm having trouble doing a basic query. So, I have this code:
function addVoterToElection(req, res) {
let query = Election.findOne({ 'name' : req.body.electionName });
let result = query.exec((err, election) => {
if(err) return err;
return res.send(election);
});
}
that works as intended, since t sends the election I need back to the requester:
{
"_id": "594408b7c94fcdc009000001",
"votechain": "594408b7c94fcdc009000002",
"name": "eleicaoteste",
"electionID": 12,
"__v": 0,
"voters": null
}
But the thing is that I need to use that object for other purposes, and I'm having trouble "extracting" it from the query.exec. If I do
let query = Election.findOne({ 'name' : req.body.electionName });
let result = query.exec((err, election) => {
if(err) return err;
return (election);
});
res.json(result);
all I get back is
{
"emitted": {},
"ended": false,
"_events": {},
"_eventsCount": 2
}
and thus I'm not able to use it for the next query that relies on having this election object working. What can I do? I know this is a fairly basic question, but I'm not sure I understand how the whole promise thing works. Thank you so much!
The problem is that you are not using the promise
right.
This is a good place to start learning about Promises
:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
The solution is very straightforward:
let query = Election.findOne({ 'name' : req.body.electionName });
let result = query.exec();
result.then((result) => {
res.json(result);
}).catch((error) => {
// console.log(err);
});
let query = Election.findOne({ 'name' : req.body.electionName });
let result = query.exec((err, election) => {
if(err) return err;
return (election);
});
res.json(result);
Query runs asynchronously (in the background), while the rest of your code executes. When query is done exec'ing, it executes the callback that takes err and election. When you're returning the result, it hasn't finished executing yet, hence your problem.
What you can do is move res.json to the body of your callback, like so:
let query = Election.findOne({ 'name' : req.body.electionName });
query.exec((err, election) => {
if(err) return err;
res.json(election);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.