0

I am trying to create an api that will create a group with members in expressjs. This is how it works till now:

Make a post request with a JSON object in req.body, using which I will create a new group. If the members array of the req.body object contains member id, add it to the group members array, else create a new user and then add its id to the array.

Basically an existing user just gets added, new user will be created and then added. For this I need to loop through the members array in the req.body and check for an object.

But the code below doesn't seem to work properly. I am getting strange results for console.log(group_info.members);. I am expecting this to contain objects with id in an array, but getting random results. Something seems to be wrong in the foreach loop. Please help me figure it out.

var express = require('express');
var router = express.Router();
var Group = require('../models/GroupModel');
var User = require('../models/UserModel');
var async = require("async");

router.post('/', function (req, res, next) {
var group_members = [];
var group_info = req.body;

//see if a member object is sent, create user for that else just add the user id to group_members array

async.forEach(group_info.members, function (member, callback) {
    if (typeof member == "object") {
        //create new user and add the _id to members array
        var user = new User(member);
        user.save(function (err) {
            if (err) return res.status(500).send(err);
            var member_object = {id: user._id};
            group_members.push(member_object);
        }).then(callback);
    } else {
        var member_object = {id: member };
        group_members.push(member_object);
        callback();
    }
}, function (err) {
    //final call back
    group_info.members = group_members; //replace the original array in request body with the new array of users
    console.log(group_info.members);
    var group = new Group(group_info);
    group.save(function (err) {
        if (err) return res.status(500).send(err);
        res.json(group);
    });
});
});
1
  • It looks like you actually want to use async.map instead of forEach which would manage the group_members array for you Commented Nov 24, 2016 at 18:20

2 Answers 2

1

Looks like you made a mistake its eachSeries not forEach, so just replace :

 async.forEach(group_info.members, function (member, callback)

with:

async.eachSeries(group_info.members, function (member, callback)

Update

As pointed out in the comments forEach is an alias for async each API, You can read the docs here,Thank You @megawac for pointing this out.

Sign up to request clarification or add additional context in comments.

2 Comments

I ended up using the async.each series. Thanks!
forEach is actually just an alias of each (caolan.github.io/async/docs.html#each)
1
var group_members = [];
var group_info = req.body;

var todo = group_info.members.length;
var done = 0;
if(todo == 0)
{
    return saveGroup(res, group_members);
}
else
{
    group_info.members.forEach(function (member, index, array) {
       if (typeof member == "object") {
            //create new user and add the _id to members array
            var user = new User(member);
            user.save(function (err, savedObject) {
                if (err || !savedObject)
                {
                    return res.status(500).send(err);
                }
                else
                {

                    var member_object = {id: savedObject._id};
                    group_members.push(member_object);
                    if(++done >= todo)
                    {
                        return saveGroup(res, group_info, group_members);
                    }
                }
            });
        } else {
           var member_object = {id: member };
           group_members.push(member_object);
           if(++done >= todo)
           {
                return saveGroup(res, group_info, group_members);
            }
        }
    });
}

function saveGroup(res, group_info, group_members)
{
    group_info.members = group_members; //replace the original array in request body with the new array of users
    console.log(group_info.members);
    var group = new Group(group_info);
    group.save(function (err) {
        if (err) return res.status(500).send(err);
        res.json(group);
    });
}

2 Comments

looks like you removed the async library all along. If I go this way, I need to handle this all in code. That was the basic idea behind using async in first place.
Use the same process (e.g todo, done) but simply call callback instead of saveGroup

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.