我正在尝试创建一个api,它将在expressjs中创建一个包含成员的组。这是它到目前为止的工作方式:
使用req.body
中的JSON对象发布帖子请求,我将使用该对象创建一个新组。如果req.body
对象的成员数组包含成员标识,则将其添加到组成员数组中,否则创建新用户,然后将其id添加到数组中。
基本上只添加现有用户,将创建新用户然后添加。为此,我需要遍历req.body
中的成员数组并检查对象。
但是下面的代码似乎没有正常工作。我console.log(group_info.members);
的结果很奇怪。我期望这包含一个数组中id
的对象,但得到随机结果。在foreach循环中似乎有些错误。请帮我搞清楚。
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);
});
});
});
答案 0 :(得分: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);
});
}
答案 1 :(得分:1)
Looks like you made a mistake its eachSeries并非forEach,所以只需替换:
async.forEach(group_info.members, function (member, callback)
使用:
async.eachSeries(group_info.members, function (member, callback)
<强>更新强>
正如评论中指出的那样 forEach 是async
each
API的别名,您可以阅读文档here,感谢@megawac指点这个。