Vivek V Dwivedi Vivek V Dwivedi - 8 days ago 7
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

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);
});
});
});

AJS AJS
Answer

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.

Comments