【问题标题】:Update 2 different collections simultaneously同时更新 2 个不同的集合
【发布时间】: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


【解决方案1】:

首先,我会远离那种设计。我会在组织中引用或嵌入用户,反之亦然,而不是同时使用两者,所以我不会遇到这样的问题(每次复制数据时都会发生)。

MongoDB 不支持同时更新或事务。所以你可以在你的代码中管理它。

所以是的,如果第二次更新失败,那么当你编写代码时,你必须回滚,如果回滚失败,你必须重试直到它成功(尽管可能有指数回退)。请记住,这可能会干扰其他请求(另一个用户尝试同时保存相同的内容)。要处理这个问题,您必须为数组中的每个条目赋予唯一性。

【讨论】:

    猜你喜欢
    • 2021-05-11
    • 2017-05-07
    • 1970-01-01
    • 1970-01-01
    • 2022-07-26
    • 2013-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多