我编写了这个服务,当我调用它时,JSON响应是组已更新,但当我检查组详细信息时,它未更新,旧的详细信息仍然存在。我不知道哪里出了问题。
这是我的代码:
app.post('/api/updateGroup/:group_id', function(req, res) {
var checkGroup = Group.findOne({'_id': req.params.group_id }).exec();
checkGroup.addBack(function(err, existingGroup) {
if (err) {
res.json({'message': err });
} else if (existingGroup) {
var group = existingGroup;
Group.findOne({'_id': req.params.group_id })
.execQ()
.then(function(existingUser) {
var friendphoneNumber = req.body.friendphoneNumber.split(',');
var friends = [];
console.log('existingUser', friendphoneNumber);
async.each(friendphoneNumber, function(phonenum, callback) {
var phonenum = phonenum.split("'")[0];
console.log('phonenum', phonenum);
User.findOne({'phoneNumber': phonenum })
.execQ()
.then(function(existingFriend) {
if (existingFriend === null) {
friends.push({'details': {'phoneNumber': phonenum } });
} else {
friends.push({'details': existingFriend });
}
})
.catch(function(err) {
console.log('err', err)
friends.push({'details': {'phoneNumber': phonenum } });
})
.done(function() {callback(); });
}, function(err) {
friends.push({'details': {'phoneNumber': friendphoneNumber } });
existingGroup.friends = friends;
existingGroup.save();
// existingGroup.update({ '_id': req.params.group_id},{ "$set": {'friends': req.body.friendphoneNumber} } , function(err) {
// existingGroup.update({'_id': req.params.group_id}, {update[[, 'friends': req.body.friendphoneNumber]}, callback]);
existingGroup.update(function(err) {
if (err) {
res.json({message: err });
} else {
res.json({success: 1, message: 'Group updated', updatedGroup: existingGroup });
}
});
});
})
.catch(function(err) {
res.json({success: 0, message: 'user id Not Match. Please try again'});
}).done(function(events) {});
} else {
callback();
}
});
});
我解决了(在一些帮助下):
async.each(friendphoneNumber, function(phonenum, callback) {
phonenum = phonenum.split("'")[0];
console.log('phonenum', phonenum);
User.findOne({
'phoneNumber': phonenum
})
.execQ()
.then(function(existingFriend) {
if(existingFriend === null) {
friends.push({
'details': {
'phoneNumber': phonenum
}
});
} else {
friends.push({'details': existingFriend});
}
})
.catch(function(err) {
console.log('err', err)
friends.push({
'details': {
'phoneNumber': phonenum
}
});
})
.done (function() {
callback();
});
}, function(err) {
friends.push({
'details': {
'phoneNumber': friendphoneNumber
}
});
group.friends = friends;
Group.update({ '_id': req.params.group_id}, { $set: { 'friends': {'details': req.body.friendphoneNumber } } }, {safe: true, upsert: true}, function (err, user) {
if (err) {
res.json({
message: err
});
} else {
res.json({
success: 1,
message: 'Group updated',
group: group
});
}
});
});
})
.catch(function(err) {
res.json({
success: 0,
message: 'user id Not Match. Please try again'
});
})
.done(function(events) {
});
}
else {
callback();
}
});