同时更新 2 个不同的集合

Update 2 different collections simultaneously

本文关键字:集合 更新      更新时间:2023-09-26

我有两个模型定义如下:

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

问题是:如果我的第二个更新方法失败,我最终会更新一个集合而不是另一个集合?有没有办法确保它们都更新了?

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

MongoDB不支持同时更新或事务。因此,您需要在代码中管理它。

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