英文:
Use mongoose transaction with passport-local-mongoose
问题
我目前正在进行一个项目,在该项目中,我需要为Mongoose中的新用户创建两个文档。其中一个文档包含用户的账户信息,即用户名和哈希值,另一个文档包含更多数据。用户的账户信息是使用passport-local-mongoose创建的。
由于任何一个文档创建过程都可能失败,我想使用Mongoose事务来实现回滚的能力。是否有办法在passport-local-mongoose中使用事务?
我想象中的代码如下,但不幸的是它不起作用。
const session = await db.startSession()
session.startTransaction()
try {
await User.register(
new User({...}), req.body.password, function(err, msg) {...},
{ session: session }
)
// 在这里创建第二个文档
await session.commitTransaction()
session.endSession()
}
catch(err) {
await session.abortTransaction()
session.endSession()
}
请注意,上面的代码片段是用于描述问题的,实际上的实现方式可能会有所不同,取决于您的应用程序结构和需求。
英文:
I'm currently working on a project where I need to create two documents for new users in Mongoose. One of these documents contains the user's account information, i.e. username and hash, the other document contains further data. The user's account information is created using passport-local-mongoose.
Since either document creation process could fail, I want to use Mongoose transactions to be able to roll back. Is there a way to use transactions with passport-local-mongoose?
I was imagining something like this, but unfortunately it doesn't work.
const session = await db.startSession()
session.startTransaction()
try {
await User.register(
new User({...}), req.body.password, function(err, msg) {...},
{ session: session }
)
// Create second document here
await session.commitTransaction()
session.endSession()
}
catch(err) {
await session.abortTransaction()
session.endSession()
}
答案1
得分: 1
我找到了如何做到这一点。我必须以不同的方式注册用户,而不是使用register
函数。
const session = await db.startSession()
session.startTransaction()
try {
const newUser = new User({...})
await newUser.setPassword(req.body.password)
await newUser.save({ session: session })
await session.commitTransaction()
session.endSession()
}
catch(err) { ... }
英文:
I figured out how to do it. I had to register the user a different way than by using the register
function.
const session = await db.startSession()
session.startTransaction()
try {
const newUser = new User({...})
await newUser.setPassword(req.body.password)
await newUser.save({ session: session })
await session.commitTransaction()
session.endSession()
}
catch(err) { ... }
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论