gpt4 book ai didi

javascript - Mongoose 如何发送交易多个集合

转载 作者:行者123 更新时间:2023-12-05 08:46:32 26 4
gpt4 key购买 nike

旁注 我使用以下代码连接到数据库:

const mongoose = require('mongoose');

const connectDB = (url) => {
return mongoose.connect(url);
}

问题描述:我有两个不同的收藏。 findByIdAndUpdatecreate 操作都必须作为原子操作运行。这应该可以通过 Mongoose 交易实现。

const registerCustomer = async (req, res) => {
await CustomerRegistrationCode.findByIdAndUpdate(req.body._id, { used: true });
const customer = await Customer.create({firstName: req.body.firstName});
}

我尝试了什么:

const registerCustomer = async (req, res) => {
const session = await mongoose.startSession();
await session.startTransaction();
try {
await CustomerRegistrationCode.findByIdAndUpdate(req.body._id, { used: true }); //updates even though
const customer = await Customer.create({ firstName: req.body.firstName });// this line will throw error
await session.commitTransaction();
session.endSession();
} catch (error) {
console.error('abort transaction');
await session.abortTransaction();
session.endSession();
throw error;
}
}

问题 即使 Customer.create 方法抛出错误,CustomerRegistrationCode 集合也会更新。如何解决?

了解 MongoDB 事务的新方法 失败,但这是来自 https://mongoosejs.com/docs/transactions.html 的官方代码

const mongoose = require('mongoose');
const debugMongo = async () => {
const db = await mongoose.createConnection("mongodb://localhost:27017/mongotest");
const Customer = db.model('Customer', new mongoose.Schema({ name: String }));
const session = await db.startSession();
session.startTransaction();
await Customer.create([{ name: 'Test' }], { session: session }); //(node:20416) UnhandledPromiseRejectionWarning: MongoServerError: Transaction numbers are only allowed on a replica set member or mongos
let doc = await Customer.findOne({ name: 'Test' });
assert.ok(!doc);
doc = await Customer.findOne({ name: 'Test' }).session(session);
assert.ok(doc);
await session.commitTransaction();
doc = await Customer.findOne({ name: 'Test' });
assert.ok(doc);
session.endSession();
}

debugMongo();

Customer.create 中抛出一个错误,我不知道为什么。有人有最小的工作示例吗?

最佳答案

您以错误的方式使用交易,这就是它不起作用的原因。

您需要将 session 对象传递给您的操作。

const registerCustomer = async (req, res) => {
const session = await mongoose.startSession();
session.startTransaction();
try {
await CustomerRegistrationCode.findByIdAndUpdate(req.body._id, { used: true }, { session });
const customer = await Customer.create({ firstName: req.body.firstName }, { session });
await session.commitTransaction();
} catch (error) {
console.error('abort transaction');
await session.abortTransaction();
} finally {
session.endSession();
}
}

此外,我对您的代码进行了一些重构。

您可以阅读更多关于交易的信息 here

关于javascript - Mongoose 如何发送交易多个集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69596470/

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