I got myself tangled in handling returned data from async function such as findOne (as an example) etc and i can't seem to get it right.
In this code new_user is being created and i wanted to handle the response from the findOne function but user is Null due to async running. i tried different ways and yet i can't get my head around it.
var router = require('express').Router();
var mongoose = require('mongoose');
var user = require('../../Schemas/user');
router.get('/a', function (req, res, next) {
var new_user = new user({
"user_name": req.query.username, "first_name": req.query.firstname,
"last_name": req.query.lastname,
"email": req.query.email, "trips": []
});
user.findOne({ email: new_user.email }).exec(function (user) {
if (!user) { return res.sendStatus(401); }
else
return res.send(user);
});
});
module.exports = router;
I would assume it's the same thing but i also tried placing the find code in another page and calling it from within router.get('/a') but ended up with the same problem.
api/user.js:
new_user.checkUser(new_user.email).exec(function (user) {
if (!user) {
return res.sendStatus(401);
}
else
return res.send(user);
})
User schema:
var mongoose = require('mongoose');
var userSchema = new mongoose.Schema({
id: Number,
user_name: String,
first_name: String,
last_name: String,
email: { type: String, unique: true },
trips: [{ id: { type: Number } }]
},
{ collection: 'users' });
userSchema.methods.checkUser = function (newUser) {
return userM.findOne({ email: newUser }).exec(function (err, doc) {
return doc; //doc contains the document for sure
});
};
var userM = mongoose.model('user', userSchema);
module.exports = userM;
I know it's simple but at this point it's all a blur. I will appreciate any help.