0

I'm trying to make an API using node and express. This is the function that creates the user.

I'm not sure if I'm handling errors properly, I feel like being in a "promise hell" because of the async mongodb functions. The next thing I'm going to do is to get the inserted user's id, and I guess it's going to be another promise, another error to handle...

  exports.create = function(req, res, next) {
  var errors = [];
  var userData = req.body;

  // exit if the user didn't fill all fields
  var requiredFields = ['first_name',
                        'last_name',
                        'login',
                        'email',
                        'password',
                        'sex'];
  requiredFields.forEach(function(elem) {
    if (!userData.hasOwnProperty(elem))
      errors.push('The field \'' + elem + '\' is missing');
  });
  if (errors.length !== 0)
    res.status(400).json({errors: errors});

  // check if the user or the login are already in use
  db.connection.collection(COLLECTION_NAME).findOne({ $or: [
                              { email: userData.email },
                              { login: userData.login }
                            ]})
    .then(function(data) {
      // if there is no user (null) we can create it
      if (data === null) {
        db.collection(COLLECTION_NAME).insertOne(userData).then(function (data) {
          res.status(201).json("success");
        }, function (err) {
          res.status(400).json({errors: ["DB error: cannot create user"]});
        })
      } else {
        errors.push('An user is already registered with this email or this login.');
        if (errors.length !== 0)
          res.status(400).json({errors: errors});
      }
    }, function (err) {
      res.status(400).json({errors: errors});
    })
}

Is there a best way to do this ?

By the way, I can't use a validation library nor mongoose.

Thanks.

raph77777
  • 111
  • 1
  • 8

1 Answers1

1
  // check if the user or the login are already in use
  db.connection.collection(COLLECTION_NAME).findOne({
                        $or: [
                          { email: userData.email },
                          { login: userData.login }
 ]})
.then(function(data) {
  // if there is no user (null) we can create it
      if (data === null) {  
         return  db.collection(COLLECTION_NAME).insertOne(userData)
     }else{ 
         return new Promise.reject(0);//throw the error
     }
 }).then(function (data) {
      res.status(201).json("success");
 }, function (err) {
      res.status(400).json({errors: ["DB error: cannot create user"]
});

You could chain the promises...

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151