我有一系列文档,但我只想在每个文档都成功时保存它们。 Mongoose 有方法吗?
类似于:
Insert el[0] - success
Insert el[1] - success
Insert el[2] - fail
Delete el[1]
Delete el[0]
最佳答案
您可以使用事务来实现此目的。这是文档中的示例:
let session = null;
return Customer.createCollection().
then(() => Customer.startSession()).
then(_session => {
session = _session;
session.startTransaction();
return Customer.create([{ name: 'Test' }], { session: session });
}).
then(() => Customer.create([{ name: 'Test2' }], { session: session })).
then(() => session.abortTransaction()).
then(() => Customer.countDocuments()).
then(count => assert.strictEqual(count, 0)).
then(() => session.endSession());
您可以使用 abortTransaction
在出现错误时回滚查询。
在这里阅读更多内容: https://mongoosejs.com/docs/transactions.html https://www.mongodb.com/transactions
关于javascript - 是否有 Mongoose 方法来保存多个文档,但只有当全部成功时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62135890/