gpt4 book ai didi

node.js - 如何在 Mongoose 模型中实现事务概念?

转载 作者:太空宇宙 更新时间:2023-11-03 21:50:52 24 4
gpt4 key购买 nike

我有三个模型“userLogin.js”、“userDetail.js”和“userAddress.js”。我希望数据应该同时存储,如果发生任何错误,它应该回滚所有插入操作。这就是我所拥有的尝试过。我给我错误 user is not Defined 。当尝试修复它们时,会出现错误“架构未注册”

 const UserLogin=require("../models/userLogin");
const UserDeatil=require("../models/userDetail");

var myModelSchema1 = require('mongoose').model('UserLogin').schema;
var myModelSchema2 = require('mongoose').model('UserDeatils').schema;

exports.user_signup = (req, res, next) => {
UserLogin.find({ email: req.body.email })
.exec()
.then(user => {
if (user.length >= 1) {
return res.status(409).json({
message: "Mail exists"
});
} else {
bcrypt.hash(req.body.password, 10, (err, hash) => {
if (err) {
return res.status(500).json({
error: err
});
} else {
const user = new UserLogin({
_id: new mongoose.Types.ObjectId(),

email: req.body.email,
password: hash,
loginDate:req.body.logindate,

});
const userdetils = new UserDeatil({
_id: new mongoose.Types.ObjectId(),
userId:result.userID,
userName:req.body.username,
dob:req.body.dob,
gender:req.body.gender,
photo: req.file? req.file.path : null,
imei:req.body.imei,

});
insertUsers();



}
});
}
});
};

async function insertUsers(){
try{

const id= transaction.insert(myModelSchema1, user);
const id1= transaction.insert(myModelSchema2, userdetils);
const final = await transaction.run();

}
catch(error){

console.error(error);
const rollbackObj = await transaction.rollback().catch(console.error);
transaction.clean();
c
}

}

最佳答案

首先,当您定义用户架构时,电子邮件必须是唯一的,当您尝试使用同一电子邮件创建另一个用户文档时会失败,

通过这个约定,您可以像这样前进:

 const UserLogin=require("../models/userLogin");
const UserDeatil=require("../models/userDetail");

cosnt signup = async (req ,res)=>{
const { email , password ,...details} = req.body
const createdDocs = []
const hashedPwd = hash(password);

try{
const user = new UserLogin({ email , password: hashedPwd });

await user.save()

createdDocs.push(user)


const userDetails = new UserDetails({...details,userId:user._id});

await userDetails.save()


createdDocs.push(userDetails)

catch(err){

res.json({ status:false, message:err.message})

//emulates the rollback when any thing fails on the try flow
if(createdDocs.length){
const operationsToRollBack = createdDocs.map(doc=>doc.remove)
await Promise.all(operationsToRollBack)
}

}

关于node.js - 如何在 Mongoose 模型中实现事务概念?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58461468/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com