Mongodb Sails水线ODM中多个模型的回滚事务(用于Mongo DB)
我在Mongo数据库中使用Sails和水线ORM 我有两个模型,用户和配置文件是一对一的关系。Mongodb Sails水线ODM中多个模型的回滚事务(用于Mongo DB),mongodb,transactions,sails.js,waterline,sails-mongo,Mongodb,Transactions,Sails.js,Waterline,Sails Mongo,我在Mongo数据库中使用Sails和水线ORM 我有两个模型,用户和配置文件是一对一的关系。 下面是我为带有回滚逻辑的事务编写的代码。我认为还有比这更好的逻辑,因为目前的逻辑非常笨拙 问题: 水线或帆是否提供任何用于回滚的功能 有没有更好的办法 User.create(newUser).然后(函数(数据){ var newProfile={ displayName:data.name, 电子邮件:data.email, 用户:数据。\u id } 返回配置文件。创建(新建配置文件); }).t
下面是我为带有回滚逻辑的事务编写的代码。我认为还有比这更好的逻辑,因为目前的逻辑非常笨拙 问题:
User.create(newUser).然后(函数(数据){
var newProfile={
displayName:data.name,
电子邮件:data.email,
用户:数据。\u id
}
返回配置文件。创建(新建配置文件);
}).then(函数(profileData){
sails.log.info(“Profile数据”+JSON.stringify(profileData));
//使用配置文件信息更新用户
update(newUser.\u id,{profile:profileData.\u id})。然后(函数(updateUser){
返回UpdateUser;
},函数(err){
//如果用户更新失败,则执行回滚逻辑
})
},函数(err){
sails.log.error(“未能为用户创建配置文件。删除创建的用户”);
风险值标准={
电子邮件:data.email
}
销毁(标准)。然后(函数(用户){
sails.log.error(“删除了创建的用户”+JSON.stringify(用户));
抛出新错误(“创建用户时出错”);
},函数(err){
sails.log.error(“删除用户时出错”);
抛出新错误(“删除用户时出错”,err);
})
});
问题1:否
我很想做这样的事情:
async.waterfall([
function(callback){
User.create(newUser).then(function(data){
callback(null, data);
})
.catch(function(err){
callback(err, null, null); // don't need to rollback anything
})
},
function(data, callback){
Profile.create({
displayName: data.name,
email: data.email,
user: data._id
})
.then(function(profile){
callback(null, data, profile)
})
.create(function(err){
callback(err, data._id, null); // only need user's id
})
},
function(userData, profileData, callback){
User.update(userData._id, {profile: profileData._id})
.then(function(updatedUser){
callback(null, updatedUser);
})
.catch(function(err){
callback(err, userData._id, profileData._id); // can roll back both
})
}
], function(err, userData, profileData){
if(err) {
sails.log.error(err);
// do rollback, userData is user's ID, profileData is profile id
// if either one is undefined, then it doesn't exist
} else {
// userData is user object from the last update, return it!
}
})
我不知道它是否更好,但它看起来更可读,并且它可以处理三个写作阶段中的任何一个阶段的错误