I have a node code which adds users in a group. The models are properly structured and the request contains the field group and users with the group id and array of users mobile numbers respectively.
groupRouter.post('/adduser', Verify.verifyOrdinaryUser, function(req, res, next) {
Groups.findById(req.body.group, function(err, group) {
if(err) next(err);
if(group.admin==req.decoded._doc._id) {
for(var i=0; i<(req.body.users.length); i++){
User.findOne({mobile:req.body.users[i]}, function(err, users) {
if(err) next(err);
users.groups.push(req.body.group);
users.save(function (err, users) {
if (err) next(err);
})
group.users.push(users._id);
group.save(function (err, group) {
if(err) next(err);
})
console.log('Added user '+users.username);
})
}
res.end('Added the users successfully!');
}
})
})
Now the problem here is that the code runs as required but adds unexceptionally in the groups. Infact mostly the first user is added as a duplicate to the group.
Mostly the problem is in this part of the code maybe:
group.users.push(users._id);
group.save(function (err, group) {
if(err) next(err);
})
Or the error could be because of the code being executed asynchronously. Tried multiple fixes with no luck. Please help me find and correct the possible errors. Where am i going wrong.
via Ronak Shah
No comments:
Post a Comment