0

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.

2
  • 1
    is there any way out you can use callback function? Commented Apr 7, 2018 at 19:49
  • @prabhatmishra although Renato Gama answered the question i would appreciate any suggestions for improvement. thanks Commented Apr 7, 2018 at 19:52

1 Answer 1

1

.exec function returns in the form of (err, results), so you should change it to:

user.findOne({ email: new_user.email }).exec(function (err, user) {
  if (err) {
    return next(err);
  }

  if (!user) {
    return res.sendStatus(401); 
  }

  res.send(user);
});

EDIT: checkUser calls findOne which is an async function, so you should either use async/await syntax (1) or pass a callback (2);

// 1
userSchema.statics.checkUser = function (newUser, cb) {
    return userM.findOne({ email: newUser }).exec(cb);
};

// 2
userSchema.statics.checkUser = async function (newUser) {
    return userM.findOne({ email: newUser });
};

So you can consume it like follows;

// 1
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.checkUser(new_user, function (err, user) {
        if (err) {
          return next(err)
        }

        if (!user) { return res.sendStatus(401); }
        else
            return res.send(user);
    });
});

// 2
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": []
    });

    try {
      const user = user.checkUser(new_user)
      if (!user) { return res.sendStatus(401); }
      else
          return res.send(user);
    } catch (err) {
      next(err)
    }
});    
Sign up to request clarification or add additional context in comments.

1 Comment

can you explain how would i go about returning the doc from userSchema.methods.checkUser and using the response in api/user.js ?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.