简体   繁体   English

同时更新2个不同的集合

[英]Update 2 different collections simultaneously

I have two models defined like this: 我有两个定义如下的模型:

var OrganizationSchema = new mongoose.Schema({
    users: [mongoose.Schema.Types.ObjectId]
});

and

var UserSchema = new mongoose.Schema({
    organizations: [mongoose.Schema.types.ObjectId]
});

When a user want to join an organization I need to update both the organization collection and the user collection. 当用户想要加入组织时,我需要更新组织集合和用户集合。 I want to know what is the best way to achieve this ? 我想知道实现这个目标的最佳方法是什么? Is it worth considering the case when one update request fail ? 当一个更新请求失败时,是否值得考虑这种情况? I'm currently doing something like this (where organization is a collection instance of the model Organization): 我现在正在做这样的事情(组织是模型组织的集合实例):

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

The problem is: if my second update method fail I will end up with one collection updated and not the other ? 问题是:如果我的第二个更新方法失败,我最终会更新一个集合而不是另一个集合? Is there a way to make sure they are both updated ? 有没有办法确保它们都更新?

Well firstly, I would stay clear of that design. 首先,我会保持清晰的设计。 I would either reference or embed user in organisations and the other way around, not both of them at same time, so I wouldn't have problems like this(which happens every-time you duplicate data). 我会在组织中引用或嵌入用户,而不是同时嵌入用户,所以我不会遇到这样的问题(每次复制数据时都会发生这种情况)。

MongoDB doesn't have support for simultaneous updates, or transactions. MongoDB不支持同步更新或事务。 So you are left to manage this in your code. 因此,您需要在代码中管理它。

So yes, if the second update fails, then as you wrote your code you have to rollback, and if the rollback fails, you have to retry till it succeeds(though with exponential backoff probably). 所以是的,如果第二次更新失败,那么当您编写代码时,您必须回滚,如果回滚失败,则必须重试直到成功(尽管可能是指数退避)。 Keep in mind that might intefer with other requests(another user tries to save the same thing simultaneously). 请记住,可能会与其他请求相关(另一个用户尝试同时保存相同的内容)。 To handle that you have to give a unique to each entry in the array. 要处理它,您必须为数组中的每个条目赋予唯一性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM