Connection.prototype.transaction()
Parameters
fn «Function» Function to execute in a transaction
[options] «mongodb.TransactionOptions» Optional settings for the transaction
Returns:
- «Promise<Any>» promise that resolves to the returned value of
fn
Requires MongoDB >= 3.6.0. Executes the wrapped async function in a transaction. Mongoose will commit the transaction if the async function executes successfully and attempt to retry if there was a retriable error.
Calls the MongoDB driver’s session.withTransaction()
, but also handles resetting Mongoose document state as shown below.
Example:
const doc = new Person({ name: 'Will Riker' });
await db.transaction(async function setRank(session) {
doc.rank = 'Captain';
await doc.save({ session });
doc.isNew; // false
// Throw an error to abort the transaction
throw new Error('Oops!');
},{ readPreference: 'primary' }).catch(() => {});
// true, `transaction()` reset the document's state because the
// transaction was aborted.
doc.isNew;
当前内容版权归 mongoosejs 或其关联方所有,如需对内容或内容相关联开源项目进行关注与资助,请访问 mongoosejs .