Hey there!
I’m using mongodb transaction over the operation. I insert many documents using insertMany
in CollectionA
then i $set and $push CollectionA ids in CollectionB
a particular fields. then finally i delete few specific documents from CollectionA
Lets share an example :
try {
const session = await mongoose.startSession();
session.startTransaction();
const createPages = await CollectionA.insertMany(newPages, { session });
const pageIds = cratePages.map((page) => page.id);
await CollectionB.findByIdAndUpdate(
Id,
{ $set: { firstName: "John Doe" }, $push: { pages: { $each: pageIds } } },
{ session }
if (isDelete) {
await CollectionA.deleteMany({ _id: { $in:[1, 2, 3, 4, 5] } }, { session });
}
if (!cratePages || !updateSite) {
await session.abortTransaction();
await session.endSession();
return null;
}
await session.commitTransaction();
await session.endSession();
return cratePages;
} catch(err){
await session.abortTransaction();
await session.endSession();
throw err;
}
This is a graphql api. after running this api it’s seems work perfectly but when i test this resolvers code using mocha
and chai.js
but when i run the test some times I passed the test (means work) and some times test throw bellow error
MongoError: Unable to read from a snapshot due to pending collection catalog changes; please retry the operation.Snapshot timestamp is Timestamp(1684396773, 34).Collection minimum is Timestamp(1684396773, 36) at MessageStream.messageHandler(/usr/src / app / node_modules / mongodb / lib / cmap / connection.js: 299: 20) at MessageStream.emit(node: events: 513: 28) at MessageStream.emit(node: domain: 489: 12) at processIncomingData(/usr/src / app / node_modules / mongodb / lib / cmap / message_stream.js: 144: 12) at MessageStream._write(/usr/src / app / node_modules / mongodb / lib / cmap / message_stream.js: 42: 5) at writeOrBuffer(node: internal / streams / writable: 392: 12) at _write(node: internal / streams / writable: 333: 10) at Writable.write(node: internal / streams / writable: 337: 10) at Socket.ondata(node: internal / streams / readable: 766: 22) at Socket.emit(node: events: 513: 28) at Socket.emit(node: domain: 489: 12) at addChunk(node: internal / streams / readable: 324: 12) at readableAddChunk(node: internal / streams / readable: 297: 9) at Readable.push(node: internal / streams / readable: 234: 10) at TCP.onStreamRead(node: internal / stream_base_commons: 190: 23) { operationTime: Timestamp { _bsontype: 'Timestamp', low_: 36, high_: 1684396773 }, ok: 0, code: 246, codeName: 'SnapshotUnavailable', '$clusterTime': { clusterTime: Timestamp { _bsontype: 'Timestamp', low_: 36, high_: 1684396773 }, signature: { hash: [Binary], keyId: 0 } }, [Symbol(errorLabels)]: Set(1) { 'TransientTransactionError' } }