有没有一种Mongoose方法可以保存多个文档,但只有在全部成功时
Is there a Mongoose method to save multiple documents, but only when all success
我有一系列文档,但我只想在每个文档都成功时保存它们。有猫鼬的方法吗?
类似于:
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
我有一系列文档,但我只想在每个文档都成功时保存它们。有猫鼬的方法吗?
类似于:
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