【发布时间】:2016-06-25 03:58:44
【问题描述】:
我有两个这样定义的模型:
var OrganizationSchema = new mongoose.Schema({
users: [mongoose.Schema.Types.ObjectId]
});
和
var UserSchema = new mongoose.Schema({
organizations: [mongoose.Schema.types.ObjectId]
});
当用户想要加入组织时,我需要同时更新组织集合和用户集合。我想知道实现这一目标的最佳方法是什么?一个更新请求失败的情况是否值得考虑?我目前正在做这样的事情(其中组织是模型组织的集合实例):
User.findByIdAndUpdate(req.userSession.userId, { $push: { organizations: organization.id } }, function (err){
if (err)
{
// server error
console.log(err);
}
else
{
organization.users.push(req.userSession.userId);
organization.save(function (err){
if (err)
{
// server error we need to cancel
User.findByIdAndUpdate(req.userSession.userId, { $pull: { organizations: organization.id } }, function (err){
if (err)
{
// we got a problem one collection updated and not the other one !!
console.log(err);
}
});
}
else
{
// success
}
});
}
});
问题是:如果我的第二个更新方法失败,我最终会更新一个集合而不是另一个?有没有办法确保它们都更新?
【问题讨论】:
-
我几乎有同样的问题。希望我们能得到答案。
标签: javascript node.js mongodb express mongoose