Vivek V Dwivedi Vivek V Dwivedi - 1 year ago 88
Node.js Question

How to Iterate over array using async and foreach

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

, using which I will create a new group. If the members array of the
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
and check for an object.

But the code below doesn't seem to work properly. I am getting strange results for
. I am expecting this to contain objects with
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");'/', 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); (err) {
if (err) return res.status(500).send(err);
var member_object = {id: user._id};
} else {
var member_object = {id: member };
}, function (err) {
//final call back
group_info.members = group_members; //replace the original array in request body with the new array of users
var group = new Group(group_info); (err) {
if (err) return res.status(500).send(err);

Answer Source

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

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


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


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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download