Batches and transactions
There are no multi-call transactions (no sessions, startTransaction or commitTransaction).
Instead, every call is atomic, and bulkWrite lets one call do many things:
import { DriveDB } from '@faeizfurqan/drivedb';
const db = new DriveDB(process.env.DRIVEDB_URL!).db();const clients = db.collection('clients');
// Several writes in one call. They are applied together: if one fails, none is.const result = await clients.bulkWrite([ { insertOne: { document: { name: 'Linus', status: 'Lead' } } }, { updateOne: { filter: { name: 'Omar Farouk' }, update: { $set: { status: 'Proposal' } } } }, { deleteMany: { filter: { status: 'Lost' } } },]);console.log(result.insertedCount, result.modifiedCount, result.deletedCount);bulkWrite first checks every operation on a scratch copy. If any fails (a validation error, a
duplicate unique value…), the error is returned and nothing is changed. Otherwise
everything is applied at once. Up to 1,000 operations per call, all in one collection.
Other ways to keep data consistent:
insertMany,updateManyanddeleteManyare all-or-nothing too.findOneAndUpdatereads and changes a document in one step (for counters, queues, claiming a task).$incnever loses increments, because calls are applied one at a time.- Upserts (
updateOne(filter, update, { upsert: true })) avoid “check, then insert” races.
Made by Faeiz Furqan