From 75a54ece56aa79569ef9c35fed3b2d783ee3cea2 Mon Sep 17 00:00:00 2001 From: Brenton Partridge Date: Fri, 12 May 2017 18:35:41 -0400 Subject: [PATCH] Add Mongo hint and maxTimeMS options (#5932) --- packages/mongo/collection_tests.js | 48 ++++++++++++++++++++++++++++++ packages/mongo/mongo_driver.js | 7 +++++ 2 files changed, 55 insertions(+) diff --git a/packages/mongo/collection_tests.js b/packages/mongo/collection_tests.js index 92b2481eda..248391ce52 100644 --- a/packages/mongo/collection_tests.js +++ b/packages/mongo/collection_tests.js @@ -102,3 +102,51 @@ Tinytest.add('collection - call native find with sort function', } } ); + +Tinytest.add('collection - calling native find with maxTimeMS should timeout', + function(test) { + var collectionName = 'findOptions1' + test.id; + var collection = new Mongo.Collection(collectionName); + collection.insert({a: 1}); + + function doTest() { + return collection.find({$where: "sleep(100) || true"}, {maxTimeMS: 50}).count(); + } + if (Meteor.isServer) { + test.throws(doTest); + } + } +); + + +Tinytest.add('collection - calling native find with $reverse hint should reverse on server', + function(test) { + var collectionName = 'findOptions2' + test.id; + var collection = new Mongo.Collection(collectionName); + collection.insert({a: 1}); + collection.insert({a: 2}); + + function m(doc) { return doc.a; } + var fwd = collection.find({}, {hint: {$natural: 1}}).map(m); + var rev = collection.find({}, {hint: {$natural: -1}}).map(m); + if (Meteor.isServer) { + test.equal(fwd, rev.reverse()); + } else { + // NOTE: should be documented that hints don't work on client + test.equal(fwd, rev); + } + } +); + +Tinytest.add('collection - calling native find with good hint and maxTimeMS should succeed', + function(test) { + var collectionName = 'findOptions3' + test.id; + var collection = new Mongo.Collection(collectionName); + collection.insert({a: 1}); + if (Meteor.isServer) { + collection.rawCollection().createIndex({a: 1}); + } + + test.equal(collection.find({}, {hint: {a: 1}, maxTimeMS: 1000}).count(), 1); + } +); diff --git a/packages/mongo/mongo_driver.js b/packages/mongo/mongo_driver.js index 9ca6609cd6..ed264bc9ba 100644 --- a/packages/mongo/mongo_driver.js +++ b/packages/mongo/mongo_driver.js @@ -992,6 +992,13 @@ MongoConnection.prototype._createSynchronousCursor = function( replaceTypes(cursorDescription.selector, replaceMeteorAtomWithMongo), cursorOptions.fields, mongoOptions); + if (typeof cursorOptions.maxTimeMS !== 'undefined') { + dbCursor = dbCursor.maxTimeMS(cursorOptions.maxTimeMS); + } + if (typeof cursorOptions.hint !== 'undefined') { + dbCursor = dbCursor.hint(cursorOptions.hint); + } + return new SynchronousCursor(dbCursor, cursorDescription, options); };