NodeJS and MongoDB update array in document

时间:2015-05-24 21:17:06

标签: javascript node.js mongodb

I've following code:

exports.addUser = function(req, res, next) {
  req.assert('email', 'Email is not valid').isEmail();
  req.assert('password', 'Password must be at least 4 characters long').len(4);
  req.assert('confirmPassword', 'Passwords do not match').equals(req.body.password);
  req.assert('firstName','First Name is empty').notEmpty();
  req.assert('lastName','Last Name is empty').notEmpty();

  var errors = req.validationErrors();

  if (errors) {
    req.flash('errors', errors);
    return res.redirect('/user/account-users/add');
  }

  var user = new User({    
    email: req.body.email,
    password: req.body.password,    
    profile: {
      role: req.body.role,
      firstName: req.body.firstName,
      lastName: req.body.lastName,
      screenName: req.body.screenName,
      addressOne: req.body.addressOne,
      addressTwo: req.body.addressTwo,
      country: req.body.country,
      stateProvince: req.body.stateProvince,
      postalCode: req.body.postalCode
    }
  });

  User.findOne({ email: req.body.email }, function(err, existingUser) {
    if (existingUser) {
      req.flash('errors', { msg: 'Account with that email address already exists.' });
      return res.redirect('/user/account-users/add');
    }
    user.save(function(err) {
      if (err) return next(err);

      Account.findOne( { users: { $elemMatch: { _id: req.user._id } } }, function(err, account) {
        var accountId = account._id;
        if(err) req.flash('errors', err);
        Account.update( { _id: accountId }, { users: { $push: user } }, function(err, result){
          console.log(result)
          if (err) return next(err);
          res.redirect('/user/account-users');
        });
      }); 
    });
  });
};

Currently when user add another user to his account this code clear account document where user is added.

How to properly add new created user to Account document where current user belong?

0 个答案:

没有答案