Reputation: 1478
I'm new to mongo and node js, here's what I'm trying to do:
The API is to check if there is an existing entry in the DB, based on the query.
Problem: In scenario (a), after creating document, the API sends "null" to the client.
Suspect: .populate() & .exec() runs before the API finishes creating a new document. The snippet from the code returns null:
console.log('Inside IF' + video_res); // returns null
What's the best way to resolve this?
model_video.findOne( video_entry,
function(err, video_req) { // Send Back Object ID
if (err) res.send(err);
if (!video_req) { // Does not work
console.log('-----STATUS : No Video Found');
model_video.create(video_entry, function(err, video_res) {
console.log('Call back activated');
if (err) res.send(err);
console.log('Response is ' + video_res);
return video_res; // Does not work here!
}); // Ends - Create
console.log('Inside IF ' + video_res);
}
else { // Works
console.log('-----STATUS : Video Found')
if (err) return res.send(err);
var video_res = video_req;
console.log('Response is ' + video_res);
return video_res;
};
})
.populate('_chirps')
.exec(function(err, video_res) {
if (err) return res.send(err);
res.json(video_res);
console.log('Final Output is ' + video_res)
});
};
Your help is greatly appreciated!
Upvotes: 3
Views: 4920
Reputation: 11677
The callback exec() callback executes immediately after your .findOne query, you need to put the rest of your code in that callback. I've refactored your code to make it more inline with what you're trying to do.
model_video.findOne(video_entry)
.populate('_chirps')
.exec(function(err, video_res) {
if (err) return res.send(err);
if (video_res) {
console.log('-----STATUS : Video Found')
console.log('Response is ' + video_res);
res.json(video_res)
}
else {
console.log('-----STATUS : No Video Found');
model_video.create(video_entry, function(err, new_video_res) {
if (err) return res.send(err);
console.log('Response is ' + new_video_res);
res.json(new_video_res);
});
}
})
Upvotes: 3