简体   繁体   中英

Mongoose/MongoDB - Delete and Insert as one transaction

I wanted to delete certain set of documents in the mongo collection and insert new records, in case if the insert fails I want to rollback the delete. Basically, it is either both or none. Someone know what is the best approach for this. I'm using mongoose and nodejs.

Try to use promises. Insert one more field to your schema like isDeleted. When you delete some document set it to true and in the success of promise of delete, if the document successfully inserted delete that record permanently if you want.

Like this

db.collection.findOneAndUpdate(query)
.exec()
.then(
     // write your insert logic here
     db.collection.insert(query)
    .exec()
    .then()
    .catch(
      //if anything goes wrong set isDeleted
       //to false again. 
    )
)
.catch() 

我添加一个'隐藏'标志,然后在某些记录上将标志设置为true,然后根据插入失败或成功删除隐藏对象或取消隐藏它们

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM