javascript - 是否有 Mongoose 方法来保存多个文档,但只有当全部成功时

标签 javascript mongodb mongoose transactions atomic

我有一系列文档,但我只想在每个文档都成功时保存它们。 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/

相关文章:

javascript - JS 上的 Match() 与正则表达式返回 NULL

node.js - 如何在 Mongoose 模式中引用另一个属性

javascript - 为了让这个 beforeafter.js 插件正常工作,我缺少什么?

javascript - Angular4 http 获取解析错误

javascript - ajax setInterval效率

node.js - 是否有任何 Node 库可以重命名gridfs中的文件?

用于保留、嵌套或引用的 MongoDB 模式?

mongodb - 如何在不同的数据库中创建Meteor集合?

javascript - 编写一个更新/保存的 Mongoose 方法?

node.js - Node + mongo-native : how to find and update value in collection?