Created
May 12, 2020 08:05
-
-
Save bhunjadi/d3df29c3d2b1f8cd1a6139eeba7a6e20 to your computer and use it in GitHub Desktop.
Patch mongodb cursor.count to be used with mongo transactions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import {MongoInternals} from 'meteor/mongo'; | |
const RawCollection = MongoInternals.NpmModule.Collection; | |
const Cursor = MongoInternals.NpmModule.Cursor; | |
const CountDocumentsOperation = MongoInternals.NpmModule.Operations; | |
RawCollection.prototype.count = function (...args) { | |
return this.countDocuments(...args); | |
}; | |
const originalCount = Cursor.prototype.count; | |
Cursor.prototype.count = function (applySkipLimit, options, callback) { | |
const MongoTransactionsPackage = Package['bhunjadi:mongo-transactions']; | |
if (MongoTransactionsPackage.isInTransaction()) { | |
const args = Array.prototype.slice.call(arguments, 0); | |
callback = typeof args[args.length - 1] === 'function' ? args.pop() : undefined; | |
options = typeof args[args.length - 1] === 'object' ? args.shift() || {} : {}; | |
applySkipLimit = args.length ? args.shift() ?? true : true; | |
const {operation} = this; | |
const {options: {db}, cmd: {find, limit, skip, query}} = operation; | |
const col = db.collection(find); | |
const countDocumentsOptions = { | |
...options, | |
collation: this.cmd.collation, | |
}; | |
if (applySkipLimit) { | |
if (typeof this.cursorSkip() === 'number') countDocumentsOptions.skip = this.cursorSkip(); | |
if (typeof this.cursorLimit() === 'number') countDocumentsOptions.limit = this.cursorLimit(); | |
} | |
return col.countDocuments(query, countDocumentsOptions, callback); | |
} | |
return originalCount.call(this, applySkipLimit, options, callback); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment