New to Node and Mongoose here. I am having trouble running my mongoose findOne()
query in a synchronous fashion within a function. Here is my code:
exports.read = function(req, res){
console.log("in articles controller read()");
//try to get article creatorId and use user providerData
//name to make fullName
var userName = "";
//get article creator id
User.findOne({ '_id': req.article.creator._id }, function(err, person){
if(err) { return next(err)};
if (!person) { return next(new Error('Failed to find user'))};
console.log("found person");
//return providerData name
userName = person.providerData.name;
});
//assign username value to article creator
var splitName = userName.split(' ');
req.article.creator.fullName = userName;
req.article.creator.firstName = splitName[0] || '';
req.article.creator.lastName = splitName[1] || '';
console.log("end of read()";
res.json(req.article);
};
When I look at my console, I expect to see the logs in the following order:
- in articles controller
read()
- found person
- end of
read()
But instead, I see in my console:
- in articles controller
read()
- end of
read()
- found person
I'm assuming that this issue has to probably do with the async nature of node?
Basically, I would like to run the findOne()
query before assigning values to my req object so that I can actually have something to assign. Please help.