Source: lib/collection.js

  1. "use strict";
  2. var checkCollectionName = require('./utils').checkCollectionName
  3. , ObjectID = require('mongodb-core').BSON.ObjectID
  4. , Long = require('mongodb-core').BSON.Long
  5. , Code = require('mongodb-core').BSON.Code
  6. , f = require('util').format
  7. , AggregationCursor = require('./aggregation_cursor')
  8. , MongoError = require('mongodb-core').MongoError
  9. , shallowClone = require('./utils').shallowClone
  10. , isObject = require('./utils').isObject
  11. , toError = require('./utils').toError
  12. , normalizeHintField = require('./utils').normalizeHintField
  13. , handleCallback = require('./utils').handleCallback
  14. , decorateCommand = require('./utils').decorateCommand
  15. , formattedOrderClause = require('./utils').formattedOrderClause
  16. , ReadPreference = require('./read_preference')
  17. , CoreReadPreference = require('mongodb-core').ReadPreference
  18. , CommandCursor = require('./command_cursor')
  19. , Define = require('./metadata')
  20. , Cursor = require('./cursor')
  21. , unordered = require('./bulk/unordered')
  22. , ordered = require('./bulk/ordered')
  23. , assign = require('./utils').assign;
  24. /**
  25. * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection
  26. * allowing for insert/update/remove/find and other command operation on that MongoDB collection.
  27. *
  28. * **COLLECTION Cannot directly be instantiated**
  29. * @example
  30. * var MongoClient = require('mongodb').MongoClient,
  31. * test = require('assert');
  32. * // Connection url
  33. * var url = 'mongodb://localhost:27017/test';
  34. * // Connect using MongoClient
  35. * MongoClient.connect(url, function(err, db) {
  36. * // Create a collection we want to drop later
  37. * var col = db.collection('createIndexExample1');
  38. * // Show that duplicate records got dropped
  39. * col.find({}).toArray(function(err, items) {
  40. * test.equal(null, err);
  41. * test.equal(4, items.length);
  42. * db.close();
  43. * });
  44. * });
  45. */
  46. var mergeKeys = ['readPreference', 'ignoreUndefined'];
  47. /**
  48. * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly)
  49. * @class
  50. * @property {string} collectionName Get the collection name.
  51. * @property {string} namespace Get the full collection namespace.
  52. * @property {object} writeConcern The current write concern values.
  53. * @property {object} readConcern The current read concern values.
  54. * @property {object} hint Get current index hint for collection.
  55. * @return {Collection} a Collection instance.
  56. */
  57. var Collection = function(db, topology, dbName, name, pkFactory, options) {
  58. checkCollectionName(name);
  59. // Unpack variables
  60. var internalHint = null;
  61. var slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk;
  62. var serializeFunctions = options == null || options.serializeFunctions == null ? db.s.options.serializeFunctions : options.serializeFunctions;
  63. var raw = options == null || options.raw == null ? db.s.options.raw : options.raw;
  64. var promoteLongs = options == null || options.promoteLongs == null ? db.s.options.promoteLongs : options.promoteLongs;
  65. var promoteValues = options == null || options.promoteValues == null ? db.s.options.promoteValues : options.promoteValues;
  66. var promoteBuffers = options == null || options.promoteBuffers == null ? db.s.options.promoteBuffers : options.promoteBuffers;
  67. var readPreference = null;
  68. var collectionHint = null;
  69. var namespace = f("%s.%s", dbName, name);
  70. // Get the promiseLibrary
  71. var promiseLibrary = options.promiseLibrary;
  72. // No promise library selected fall back
  73. if(!promiseLibrary) {
  74. promiseLibrary = typeof global.Promise == 'function' ?
  75. global.Promise : require('es6-promise').Promise;
  76. }
  77. // Assign the right collection level readPreference
  78. if(options && options.readPreference) {
  79. readPreference = options.readPreference;
  80. } else if(db.options.readPreference) {
  81. readPreference = db.options.readPreference;
  82. }
  83. // Set custom primary key factory if provided
  84. pkFactory = pkFactory == null
  85. ? ObjectID
  86. : pkFactory;
  87. // Internal state
  88. this.s = {
  89. // Set custom primary key factory if provided
  90. pkFactory: pkFactory
  91. // Db
  92. , db: db
  93. // Topology
  94. , topology: topology
  95. // dbName
  96. , dbName: dbName
  97. // Options
  98. , options: options
  99. // Namespace
  100. , namespace: namespace
  101. // Read preference
  102. , readPreference: readPreference
  103. // SlaveOK
  104. , slaveOk: slaveOk
  105. // Serialize functions
  106. , serializeFunctions: serializeFunctions
  107. // Raw
  108. , raw: raw
  109. // promoteLongs
  110. , promoteLongs: promoteLongs
  111. // promoteValues
  112. , promoteValues: promoteValues
  113. // promoteBuffers
  114. , promoteBuffers: promoteBuffers
  115. // internalHint
  116. , internalHint: internalHint
  117. // collectionHint
  118. , collectionHint: collectionHint
  119. // Name
  120. , name: name
  121. // Promise library
  122. , promiseLibrary: promiseLibrary
  123. // Read Concern
  124. , readConcern: options.readConcern
  125. }
  126. }
  127. var define = Collection.define = new Define('Collection', Collection, false);
  128. Object.defineProperty(Collection.prototype, 'collectionName', {
  129. enumerable: true, get: function() { return this.s.name; }
  130. });
  131. Object.defineProperty(Collection.prototype, 'namespace', {
  132. enumerable: true, get: function() { return this.s.namespace; }
  133. });
  134. Object.defineProperty(Collection.prototype, 'readConcern', {
  135. enumerable: true, get: function() { return this.s.readConcern || {level: 'local'}; }
  136. });
  137. Object.defineProperty(Collection.prototype, 'writeConcern', {
  138. enumerable:true,
  139. get: function() {
  140. var ops = {};
  141. if(this.s.options.w != null) ops.w = this.s.options.w;
  142. if(this.s.options.j != null) ops.j = this.s.options.j;
  143. if(this.s.options.fsync != null) ops.fsync = this.s.options.fsync;
  144. if(this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout;
  145. return ops;
  146. }
  147. });
  148. /**
  149. * @ignore
  150. */
  151. Object.defineProperty(Collection.prototype, "hint", {
  152. enumerable: true
  153. , get: function () { return this.s.collectionHint; }
  154. , set: function (v) { this.s.collectionHint = normalizeHintField(v); }
  155. });
  156. /**
  157. * Creates a cursor for a query that can be used to iterate over results from MongoDB
  158. * @method
  159. * @param {object} query The cursor query object.
  160. * @throws {MongoError}
  161. * @return {Cursor}
  162. */
  163. Collection.prototype.find = function() {
  164. var options
  165. , args = Array.prototype.slice.call(arguments, 0)
  166. , has_callback = typeof args[args.length - 1] === 'function'
  167. , has_weird_callback = typeof args[0] === 'function'
  168. , callback = has_callback ? args.pop() : (has_weird_callback ? args.shift() : null)
  169. , len = args.length
  170. , selector = len >= 1 ? args[0] : {}
  171. , fields = len >= 2 ? args[1] : undefined;
  172. if(len === 1 && has_weird_callback) {
  173. // backwards compat for callback?, options case
  174. selector = {};
  175. options = args[0];
  176. }
  177. if(len === 2 && fields !== undefined && !Array.isArray(fields)) {
  178. var fieldKeys = Object.keys(fields);
  179. var is_option = false;
  180. for(var i = 0; i < fieldKeys.length; i++) {
  181. if(testForFields[fieldKeys[i]] != null) {
  182. is_option = true;
  183. break;
  184. }
  185. }
  186. if(is_option) {
  187. options = fields;
  188. fields = undefined;
  189. } else {
  190. options = {};
  191. }
  192. } else if(len === 2 && Array.isArray(fields) && !Array.isArray(fields[0])) {
  193. var newFields = {};
  194. // Rewrite the array
  195. for(i = 0; i < fields.length; i++) {
  196. newFields[fields[i]] = 1;
  197. }
  198. // Set the fields
  199. fields = newFields;
  200. }
  201. if(3 === len) {
  202. options = args[2];
  203. }
  204. // Ensure selector is not null
  205. selector = selector == null ? {} : selector;
  206. // Validate correctness off the selector
  207. var object = selector;
  208. if(Buffer.isBuffer(object)) {
  209. var object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
  210. if(object_size != object.length) {
  211. var error = new Error("query selector raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
  212. error.name = 'MongoError';
  213. throw error;
  214. }
  215. }
  216. // Validate correctness of the field selector
  217. object = fields;
  218. if(Buffer.isBuffer(object)) {
  219. object_size = object[0] | object[1] << 8 | object[2] << 16 | object[3] << 24;
  220. if(object_size != object.length) {
  221. error = new Error("query fields raw message size does not match message header size [" + object.length + "] != [" + object_size + "]");
  222. error.name = 'MongoError';
  223. throw error;
  224. }
  225. }
  226. // Check special case where we are using an objectId
  227. if(selector != null && selector._bsontype == 'ObjectID') {
  228. selector = {_id:selector};
  229. }
  230. // If it's a serialized fields field we need to just let it through
  231. // user be warned it better be good
  232. if(options && options.fields && !(Buffer.isBuffer(options.fields))) {
  233. fields = {};
  234. if(Array.isArray(options.fields)) {
  235. if(!options.fields.length) {
  236. fields['_id'] = 1;
  237. } else {
  238. var l = options.fields.length;
  239. for (i = 0; i < l; i++) {
  240. fields[options.fields[i]] = 1;
  241. }
  242. }
  243. } else {
  244. fields = options.fields;
  245. }
  246. }
  247. if (!options) options = {};
  248. var newOptions = {};
  249. // Make a shallow copy of the collection options
  250. for(var key in this.s.options) {
  251. if(mergeKeys.indexOf(key) != -1) {
  252. newOptions[key] = this.s.options[key];
  253. }
  254. }
  255. // Make a shallow copy of options
  256. for (var key in options) {
  257. newOptions[key] = options[key];
  258. }
  259. // Unpack options
  260. newOptions.skip = len > 3 ? args[2] : options.skip ? options.skip : 0;
  261. newOptions.limit = len > 3 ? args[3] : options.limit ? options.limit : 0;
  262. newOptions.raw = options.raw != null && typeof options.raw === 'boolean' ? options.raw : this.s.raw;
  263. newOptions.hint = options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint;
  264. newOptions.timeout = len == 5 ? args[4] : typeof options.timeout === 'undefined' ? undefined : options.timeout;
  265. // // If we have overridden slaveOk otherwise use the default db setting
  266. newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk;
  267. // Add read preference if needed
  268. newOptions = getReadPreference(this, newOptions, this.s.db, this);
  269. // Set slave ok to true if read preference different from primary
  270. if(newOptions.readPreference != null
  271. && (newOptions.readPreference != 'primary' || newOptions.readPreference.mode != 'primary')) {
  272. newOptions.slaveOk = true;
  273. }
  274. // Ensure the query is an object
  275. if(selector != null && typeof selector != 'object') {
  276. throw MongoError.create({message: "query selector must be an object", driver:true });
  277. }
  278. // Build the find command
  279. var findCommand = {
  280. find: this.s.namespace
  281. , limit: newOptions.limit
  282. , skip: newOptions.skip
  283. , query: selector
  284. }
  285. // Ensure we use the right await data option
  286. if(typeof newOptions.awaitdata == 'boolean') {
  287. newOptions.awaitData = newOptions.awaitdata
  288. }
  289. // Translate to new command option noCursorTimeout
  290. if(typeof newOptions.timeout == 'boolean') newOptions.noCursorTimeout = newOptions.timeout;
  291. // Merge in options to command
  292. for(var name in newOptions) {
  293. if(newOptions[name] != null) findCommand[name] = newOptions[name];
  294. }
  295. // Format the fields
  296. var formatFields = function(fields) {
  297. var object = {};
  298. if(Array.isArray(fields)) {
  299. for(var i = 0; i < fields.length; i++) {
  300. if(Array.isArray(fields[i])) {
  301. object[fields[i][0]] = fields[i][1];
  302. } else {
  303. object[fields[i][0]] = 1;
  304. }
  305. }
  306. } else {
  307. object = fields;
  308. }
  309. return object;
  310. }
  311. // Special treatment for the fields selector
  312. if(fields) findCommand.fields = formatFields(fields);
  313. // Add db object to the new options
  314. newOptions.db = this.s.db;
  315. // Add the promise library
  316. newOptions.promiseLibrary = this.s.promiseLibrary;
  317. // Set raw if available at collection level
  318. if(newOptions.raw == null && typeof this.s.raw == 'boolean') newOptions.raw = this.s.raw;
  319. // Set promoteLongs if available at collection level
  320. if(newOptions.promoteLongs == null && typeof this.s.promoteLongs == 'boolean') newOptions.promoteLongs = this.s.promoteLongs;
  321. if(newOptions.promoteValues == null && typeof this.s.promoteValues == 'boolean') newOptions.promoteValues = this.s.promoteValues;
  322. if(newOptions.promoteBuffers == null && typeof this.s.promoteBuffers == 'boolean') newOptions.promoteBuffers = this.s.promoteBuffers;
  323. // Sort options
  324. if(findCommand.sort) {
  325. findCommand.sort = formattedOrderClause(findCommand.sort);
  326. }
  327. // Set the readConcern
  328. if(this.s.readConcern) {
  329. findCommand.readConcern = this.s.readConcern;
  330. }
  331. // Decorate find command with collation options
  332. decorateWithCollation(findCommand, this, options);
  333. // Create the cursor
  334. if(typeof callback == 'function') return handleCallback(callback, null, this.s.topology.cursor(this.s.namespace, findCommand, newOptions));
  335. return this.s.topology.cursor(this.s.namespace, findCommand, newOptions);
  336. }
  337. define.classMethod('find', {callback: false, promise:false, returns: [Cursor]});
  338. /**
  339. * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field,
  340. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  341. * can be overridden by setting the **forceServerObjectId** flag.
  342. *
  343. * @method
  344. * @param {object} doc Document to insert.
  345. * @param {object} [options=null] Optional settings.
  346. * @param {(number|string)} [options.w=null] The write concern.
  347. * @param {number} [options.wtimeout=null] The write concern timeout.
  348. * @param {boolean} [options.j=false] Specify a journal write concern.
  349. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  350. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
  351. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  352. * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback
  353. * @return {Promise} returns Promise if no callback passed
  354. */
  355. Collection.prototype.insertOne = function(doc, options, callback) {
  356. var self = this;
  357. if(typeof options == 'function') callback = options, options = {};
  358. options = options || {};
  359. if(Array.isArray(doc) && typeof callback == 'function') {
  360. return callback(MongoError.create({message: 'doc parameter must be an object', driver:true }));
  361. } else if(Array.isArray(doc)) {
  362. return new this.s.promiseLibrary(function(resolve, reject) {
  363. reject(MongoError.create({message: 'doc parameter must be an object', driver:true }));
  364. });
  365. }
  366. // Add ignoreUndefined
  367. if(this.s.options.ignoreUndefined) {
  368. options = shallowClone(options);
  369. options.ignoreUndefined = this.s.options.ignoreUndefined;
  370. }
  371. // Execute using callback
  372. if(typeof callback == 'function') return insertOne(self, doc, options, callback);
  373. // Return a Promise
  374. return new this.s.promiseLibrary(function(resolve, reject) {
  375. insertOne(self, doc, options, function(err, r) {
  376. if(err) return reject(err);
  377. resolve(r);
  378. });
  379. });
  380. }
  381. var insertOne = function(self, doc, options, callback) {
  382. insertDocuments(self, [doc], options, function(err, r) {
  383. if(callback == null) return;
  384. if(err && callback) return callback(err);
  385. // Workaround for pre 2.6 servers
  386. if(r == null) return callback(null, {result: {ok:1}});
  387. // Add values to top level to ensure crud spec compatibility
  388. r.insertedCount = r.result.n;
  389. r.insertedId = doc._id;
  390. if(callback) callback(null, r);
  391. });
  392. }
  393. var mapInsertManyResults = function(docs, r) {
  394. var ids = r.getInsertedIds();
  395. var keys = Object.keys(ids);
  396. var finalIds = new Array(keys.length);
  397. for(var i = 0; i < keys.length; i++) {
  398. if(ids[keys[i]]._id) {
  399. finalIds[ids[keys[i]].index] = ids[keys[i]]._id;
  400. }
  401. }
  402. var finalResult = {
  403. result: {ok: 1, n: r.insertedCount},
  404. ops: docs,
  405. insertedCount: r.insertedCount,
  406. insertedIds: finalIds
  407. };
  408. if(r.getLastOp()) {
  409. finalResult.result.opTime = r.getLastOp();
  410. }
  411. return finalResult;
  412. }
  413. define.classMethod('insertOne', {callback: true, promise:true});
  414. /**
  415. * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field,
  416. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  417. * can be overridden by setting the **forceServerObjectId** flag.
  418. *
  419. * @method
  420. * @param {object[]} docs Documents to insert.
  421. * @param {object} [options=null] Optional settings.
  422. * @param {(number|string)} [options.w=null] The write concern.
  423. * @param {number} [options.wtimeout=null] The write concern timeout.
  424. * @param {boolean} [options.j=false] Specify a journal write concern.
  425. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  426. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
  427. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  428. * @param {boolean} [options.ordered=true] If true, when an insert fails, don't execute the remaining writes. If false, continue with remaining inserts when one fails.
  429. * @param {Collection~insertWriteOpCallback} [callback] The command result callback
  430. * @return {Promise} returns Promise if no callback passed
  431. */
  432. Collection.prototype.insertMany = function(docs, options, callback) {
  433. var self = this;
  434. if(typeof options == 'function') callback = options, options = {};
  435. options = options ? shallowClone(options) : {ordered:true};
  436. if(!Array.isArray(docs) && typeof callback == 'function') {
  437. return callback(MongoError.create({message: 'docs parameter must be an array of documents', driver:true }));
  438. } else if(!Array.isArray(docs)) {
  439. return new this.s.promiseLibrary(function(resolve, reject) {
  440. reject(MongoError.create({message: 'docs parameter must be an array of documents', driver:true }));
  441. });
  442. }
  443. // Get the write concern options
  444. if(typeof options.checkKeys != 'boolean') {
  445. options.checkKeys = true;
  446. }
  447. // If keep going set unordered
  448. options['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions;
  449. // Set up the force server object id
  450. var forceServerObjectId = typeof options.forceServerObjectId == 'boolean'
  451. ? options.forceServerObjectId : self.s.db.options.forceServerObjectId;
  452. // Do we want to force the server to assign the _id key
  453. if(forceServerObjectId !== true) {
  454. // Add _id if not specified
  455. for(var i = 0; i < docs.length; i++) {
  456. if(docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk();
  457. }
  458. }
  459. // Generate the bulk write operations
  460. var operations = [{
  461. insertMany: docs
  462. }];
  463. // Execute using callback
  464. if(typeof callback == 'function') return bulkWrite(self, operations, options, function(err, r) {
  465. if(err) return callback(err, r);
  466. callback(null, mapInsertManyResults(docs, r));
  467. });
  468. // Return a Promise
  469. return new this.s.promiseLibrary(function(resolve, reject) {
  470. bulkWrite(self, operations, options, function(err, r) {
  471. if(err) return reject(err);
  472. resolve(mapInsertManyResults(docs, r));
  473. });
  474. });
  475. }
  476. define.classMethod('insertMany', {callback: true, promise:true});
  477. /**
  478. * @typedef {Object} Collection~BulkWriteOpResult
  479. * @property {number} insertedCount Number of documents inserted.
  480. * @property {number} matchedCount Number of documents matched for update.
  481. * @property {number} modifiedCount Number of documents modified.
  482. * @property {number} deletedCount Number of documents deleted.
  483. * @property {number} upsertedCount Number of documents upserted.
  484. * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation
  485. * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation
  486. * @property {object} result The command result object.
  487. */
  488. /**
  489. * The callback format for inserts
  490. * @callback Collection~bulkWriteOpCallback
  491. * @param {MongoError} error An error instance representing the error during the execution.
  492. * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully.
  493. */
  494. /**
  495. * Perform a bulkWrite operation without a fluent API
  496. *
  497. * Legal operation types are
  498. *
  499. * { insertOne: { document: { a: 1 } } }
  500. *
  501. * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
  502. *
  503. * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
  504. *
  505. * { deleteOne: { filter: {c:1} } }
  506. *
  507. * { deleteMany: { filter: {c:1} } }
  508. *
  509. * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}}
  510. *
  511. * If documents passed in do not contain the **_id** field,
  512. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  513. * can be overridden by setting the **forceServerObjectId** flag.
  514. *
  515. * @method
  516. * @param {object[]} operations Bulk operations to perform.
  517. * @param {object} [options=null] Optional settings.
  518. * @param {(number|string)} [options.w=null] The write concern.
  519. * @param {number} [options.wtimeout=null] The write concern timeout.
  520. * @param {boolean} [options.j=false] Specify a journal write concern.
  521. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  522. * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion.
  523. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  524. * @param {Collection~bulkWriteOpCallback} [callback] The command result callback
  525. * @return {Promise} returns Promise if no callback passed
  526. */
  527. Collection.prototype.bulkWrite = function(operations, options, callback) {
  528. var self = this;
  529. if(typeof options == 'function') callback = options, options = {};
  530. options = options || {ordered:true};
  531. if(!Array.isArray(operations)) {
  532. throw MongoError.create({message: "operations must be an array of documents", driver:true });
  533. }
  534. // Execute using callback
  535. if(typeof callback == 'function') return bulkWrite(self, operations, options, callback);
  536. // Return a Promise
  537. return new this.s.promiseLibrary(function(resolve, reject) {
  538. bulkWrite(self, operations, options, function(err, r) {
  539. if(err && r == null) return reject(err);
  540. resolve(r);
  541. });
  542. });
  543. }
  544. var bulkWrite = function(self, operations, options, callback) {
  545. // Add ignoreUndefined
  546. if(self.s.options.ignoreUndefined) {
  547. options = shallowClone(options);
  548. options.ignoreUndefined = self.s.options.ignoreUndefined;
  549. }
  550. // Create the bulk operation
  551. var bulk = options.ordered == true || options.ordered == null ? self.initializeOrderedBulkOp(options) : self.initializeUnorderedBulkOp(options);
  552. // Do we have a collation
  553. var collation = false;
  554. // for each op go through and add to the bulk
  555. try {
  556. for(var i = 0; i < operations.length; i++) {
  557. // Get the operation type
  558. var key = Object.keys(operations[i])[0];
  559. // Check if we have a collation
  560. if(operations[i][key].collation) {
  561. collation = true;
  562. }
  563. // Pass to the raw bulk
  564. bulk.raw(operations[i]);
  565. }
  566. } catch(err) {
  567. return callback(err, null);
  568. }
  569. // Final options for write concern
  570. var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options);
  571. var writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {};
  572. var capabilities = self.s.topology.capabilities();
  573. // Did the user pass in a collation, check if our write server supports it
  574. if(collation && capabilities && !capabilities.commandsTakeCollation) {
  575. return callback(new MongoError(f('server/primary/mongos does not support collation')));
  576. }
  577. // Execute the bulk
  578. bulk.execute(writeCon, function(err, r) {
  579. // We have connection level error
  580. if(!r && err) return callback(err, null);
  581. // We have single error
  582. if(r && r.hasWriteErrors() && r.getWriteErrorCount() == 1) {
  583. return callback(toError(r.getWriteErrorAt(0)), r);
  584. }
  585. r.insertedCount = r.nInserted;
  586. r.matchedCount = r.nMatched;
  587. r.modifiedCount = r.nModified || 0;
  588. r.deletedCount = r.nRemoved;
  589. r.upsertedCount = r.getUpsertedIds().length;
  590. r.upsertedIds = {};
  591. r.insertedIds = {};
  592. // Update the n
  593. r.n = r.insertedCount;
  594. // Inserted documents
  595. var inserted = r.getInsertedIds();
  596. // Map inserted ids
  597. for(var i = 0; i < inserted.length; i++) {
  598. r.insertedIds[inserted[i].index] = inserted[i]._id;
  599. }
  600. // Upserted documents
  601. var upserted = r.getUpsertedIds();
  602. // Map upserted ids
  603. for(i = 0; i < upserted.length; i++) {
  604. r.upsertedIds[upserted[i].index] = upserted[i]._id;
  605. }
  606. // Check if we have write errors
  607. if(r.hasWriteErrors()) {
  608. // Get all the errors
  609. var errors = r.getWriteErrors();
  610. // Return the MongoError object
  611. return callback(toError({
  612. message: 'write operation failed', code: errors[0].code, writeErrors: errors
  613. }), r);
  614. }
  615. // Check if we have a writeConcern error
  616. if(r.getWriteConcernError()) {
  617. // Return the MongoError object
  618. return callback(toError(r.getWriteConcernError()), r);
  619. }
  620. // Return the results
  621. callback(null, r);
  622. });
  623. }
  624. var insertDocuments = function(self, docs, options, callback) {
  625. if(typeof options == 'function') callback = options, options = {};
  626. options = options || {};
  627. // Ensure we are operating on an array op docs
  628. docs = Array.isArray(docs) ? docs : [docs];
  629. // Get the write concern options
  630. var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options);
  631. if(typeof finalOptions.checkKeys != 'boolean') finalOptions.checkKeys = true;
  632. // If keep going set unordered
  633. if(finalOptions.keepGoing == true) finalOptions.ordered = false;
  634. finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions;
  635. // Set up the force server object id
  636. var forceServerObjectId = typeof options.forceServerObjectId == 'boolean'
  637. ? options.forceServerObjectId : self.s.db.options.forceServerObjectId;
  638. // Add _id if not specified
  639. if(forceServerObjectId !== true){
  640. for(var i = 0; i < docs.length; i++) {
  641. if(docs[i]._id === void 0) docs[i]._id = self.s.pkFactory.createPk();
  642. }
  643. }
  644. // File inserts
  645. self.s.topology.insert(self.s.namespace, docs, finalOptions, function(err, result) {
  646. if(callback == null) return;
  647. if(err) return handleCallback(callback, err);
  648. if(result == null) return handleCallback(callback, null, null);
  649. if(result.result.code) return handleCallback(callback, toError(result.result));
  650. if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0]));
  651. // Add docs to the list
  652. result.ops = docs;
  653. // Return the results
  654. handleCallback(callback, null, result);
  655. });
  656. }
  657. define.classMethod('bulkWrite', {callback: true, promise:true});
  658. /**
  659. * @typedef {Object} Collection~WriteOpResult
  660. * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany
  661. * @property {object} connection The connection object used for the operation.
  662. * @property {object} result The command result object.
  663. */
  664. /**
  665. * The callback format for inserts
  666. * @callback Collection~writeOpCallback
  667. * @param {MongoError} error An error instance representing the error during the execution.
  668. * @param {Collection~WriteOpResult} result The result object if the command was executed successfully.
  669. */
  670. /**
  671. * @typedef {Object} Collection~insertWriteOpResult
  672. * @property {Number} insertedCount The total amount of documents inserted.
  673. * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany
  674. * @property {ObjectId[]} insertedIds All the generated _id's for the inserted documents.
  675. * @property {object} connection The connection object used for the operation.
  676. * @property {object} result The raw command result object returned from MongoDB (content might vary by server version).
  677. * @property {Number} result.ok Is 1 if the command executed correctly.
  678. * @property {Number} result.n The total count of documents inserted.
  679. */
  680. /**
  681. * @typedef {Object} Collection~insertOneWriteOpResult
  682. * @property {Number} insertedCount The total amount of documents inserted.
  683. * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany
  684. * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation.
  685. * @property {object} connection The connection object used for the operation.
  686. * @property {object} result The raw command result object returned from MongoDB (content might vary by server version).
  687. * @property {Number} result.ok Is 1 if the command executed correctly.
  688. * @property {Number} result.n The total count of documents inserted.
  689. */
  690. /**
  691. * The callback format for inserts
  692. * @callback Collection~insertWriteOpCallback
  693. * @param {MongoError} error An error instance representing the error during the execution.
  694. * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully.
  695. */
  696. /**
  697. * The callback format for inserts
  698. * @callback Collection~insertOneWriteOpCallback
  699. * @param {MongoError} error An error instance representing the error during the execution.
  700. * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully.
  701. */
  702. /**
  703. * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field,
  704. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  705. * can be overridden by setting the **forceServerObjectId** flag.
  706. *
  707. * @method
  708. * @param {(object|object[])} docs Documents to insert.
  709. * @param {object} [options=null] Optional settings.
  710. * @param {(number|string)} [options.w=null] The write concern.
  711. * @param {number} [options.wtimeout=null] The write concern timeout.
  712. * @param {boolean} [options.j=false] Specify a journal write concern.
  713. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  714. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
  715. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  716. * @param {Collection~insertWriteOpCallback} [callback] The command result callback
  717. * @return {Promise} returns Promise if no callback passed
  718. * @deprecated Use insertOne, insertMany or bulkWrite
  719. */
  720. Collection.prototype.insert = function(docs, options, callback) {
  721. if(typeof options == 'function') callback = options, options = {};
  722. options = options || {ordered:false};
  723. docs = !Array.isArray(docs) ? [docs] : docs;
  724. if(options.keepGoing == true) {
  725. options.ordered = false;
  726. }
  727. return this.insertMany(docs, options, callback);
  728. }
  729. define.classMethod('insert', {callback: true, promise:true});
  730. /**
  731. * @typedef {Object} Collection~updateWriteOpResult
  732. * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version.
  733. * @property {Number} result.ok Is 1 if the command executed correctly.
  734. * @property {Number} result.n The total count of documents scanned.
  735. * @property {Number} result.nModified The total count of documents modified.
  736. * @property {Object} connection The connection object used for the operation.
  737. * @property {Number} matchedCount The number of documents that matched the filter.
  738. * @property {Number} modifiedCount The number of documents that were modified.
  739. * @property {Number} upsertedCount The number of documents upserted.
  740. * @property {Object} upsertedId The upserted id.
  741. * @property {ObjectId} upsertedId._id The upserted _id returned from the server.
  742. */
  743. /**
  744. * The callback format for inserts
  745. * @callback Collection~updateWriteOpCallback
  746. * @param {MongoError} error An error instance representing the error during the execution.
  747. * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully.
  748. */
  749. /**
  750. * Update a single document on MongoDB
  751. * @method
  752. * @param {object} filter The Filter used to select the document to update
  753. * @param {object} update The update operations to be applied to the document
  754. * @param {object} [options=null] Optional settings.
  755. * @param {boolean} [options.upsert=false] Update operation is an upsert.
  756. * @param {(number|string)} [options.w=null] The write concern.
  757. * @param {number} [options.wtimeout=null] The write concern timeout.
  758. * @param {boolean} [options.j=false] Specify a journal write concern.
  759. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  760. * @param {Collection~updateWriteOpCallback} [callback] The command result callback
  761. * @return {Promise} returns Promise if no callback passed
  762. */
  763. Collection.prototype.updateOne = function(filter, update, options, callback) {
  764. var self = this;
  765. if(typeof options == 'function') callback = options, options = {};
  766. options = shallowClone(options)
  767. // Add ignoreUndefined
  768. if(this.s.options.ignoreUndefined) {
  769. options = shallowClone(options);
  770. options.ignoreUndefined = this.s.options.ignoreUndefined;
  771. }
  772. // Execute using callback
  773. if(typeof callback == 'function') return updateOne(self, filter, update, options, callback);
  774. // Return a Promise
  775. return new this.s.promiseLibrary(function(resolve, reject) {
  776. updateOne(self, filter, update, options, function(err, r) {
  777. if(err) return reject(err);
  778. resolve(r);
  779. });
  780. });
  781. }
  782. var updateOne = function(self, filter, update, options, callback) {
  783. // Set single document update
  784. options.multi = false;
  785. // Execute update
  786. updateDocuments(self, filter, update, options, function(err, r) {
  787. if(callback == null) return;
  788. if(err && callback) return callback(err);
  789. if(r == null) return callback(null, {result: {ok:1}});
  790. r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n;
  791. r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null;
  792. r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0;
  793. r.matchedCount = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n;
  794. if(callback) callback(null, r);
  795. });
  796. }
  797. define.classMethod('updateOne', {callback: true, promise:true});
  798. /**
  799. * Replace a document on MongoDB
  800. * @method
  801. * @param {object} filter The Filter used to select the document to update
  802. * @param {object} doc The Document that replaces the matching document
  803. * @param {object} [options=null] Optional settings.
  804. * @param {boolean} [options.upsert=false] Update operation is an upsert.
  805. * @param {(number|string)} [options.w=null] The write concern.
  806. * @param {number} [options.wtimeout=null] The write concern timeout.
  807. * @param {boolean} [options.j=false] Specify a journal write concern.
  808. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  809. * @param {Collection~updateWriteOpCallback} [callback] The command result callback
  810. * @return {Promise} returns Promise if no callback passed
  811. */
  812. Collection.prototype.replaceOne = function(filter, doc, options, callback) {
  813. var self = this;
  814. if(typeof options == 'function') callback = options, options = {};
  815. options = shallowClone(options)
  816. // Add ignoreUndefined
  817. if(this.s.options.ignoreUndefined) {
  818. options = shallowClone(options);
  819. options.ignoreUndefined = this.s.options.ignoreUndefined;
  820. }
  821. // Execute using callback
  822. if(typeof callback == 'function') return replaceOne(self, filter, doc, options, callback);
  823. // Return a Promise
  824. return new this.s.promiseLibrary(function(resolve, reject) {
  825. replaceOne(self, filter, doc, options, function(err, r) {
  826. if(err) return reject(err);
  827. resolve(r);
  828. });
  829. });
  830. }
  831. var replaceOne = function(self, filter, doc, options, callback) {
  832. // Set single document update
  833. options.multi = false;
  834. // Execute update
  835. updateDocuments(self, filter, doc, options, function(err, r) {
  836. if(callback == null) return;
  837. if(err && callback) return callback(err);
  838. if(r == null) return callback(null, {result: {ok:1}});
  839. r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n;
  840. r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null;
  841. r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0;
  842. r.matchedCount = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n;
  843. r.ops = [doc];
  844. if(callback) callback(null, r);
  845. });
  846. }
  847. define.classMethod('replaceOne', {callback: true, promise:true});
  848. /**
  849. * Update multiple documents on MongoDB
  850. * @method
  851. * @param {object} filter The Filter used to select the document to update
  852. * @param {object} update The update operations to be applied to the document
  853. * @param {object} [options=null] Optional settings.
  854. * @param {boolean} [options.upsert=false] Update operation is an upsert.
  855. * @param {(number|string)} [options.w=null] The write concern.
  856. * @param {number} [options.wtimeout=null] The write concern timeout.
  857. * @param {boolean} [options.j=false] Specify a journal write concern.
  858. * @param {Collection~updateWriteOpCallback} [callback] The command result callback
  859. * @return {Promise} returns Promise if no callback passed
  860. */
  861. Collection.prototype.updateMany = function(filter, update, options, callback) {
  862. var self = this;
  863. if(typeof options == 'function') callback = options, options = {};
  864. options = shallowClone(options)
  865. // Add ignoreUndefined
  866. if(this.s.options.ignoreUndefined) {
  867. options = shallowClone(options);
  868. options.ignoreUndefined = this.s.options.ignoreUndefined;
  869. }
  870. // Execute using callback
  871. if(typeof callback == 'function') return updateMany(self, filter, update, options, callback);
  872. // Return a Promise
  873. return new this.s.promiseLibrary(function(resolve, reject) {
  874. updateMany(self, filter, update, options, function(err, r) {
  875. if(err) return reject(err);
  876. resolve(r);
  877. });
  878. });
  879. }
  880. var updateMany = function(self, filter, update, options, callback) {
  881. // Set single document update
  882. options.multi = true;
  883. // Execute update
  884. updateDocuments(self, filter, update, options, function(err, r) {
  885. if(callback == null) return;
  886. if(err && callback) return callback(err);
  887. if(r == null) return callback(null, {result: {ok:1}});
  888. r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n;
  889. r.upsertedId = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? r.result.upserted[0] : null;
  890. r.upsertedCount = Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0;
  891. r.matchedCount = Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n;
  892. if(callback) callback(null, r);
  893. });
  894. }
  895. define.classMethod('updateMany', {callback: true, promise:true});
  896. var updateDocuments = function(self, selector, document, options, callback) {
  897. if('function' === typeof options) callback = options, options = null;
  898. if(options == null) options = {};
  899. if(!('function' === typeof callback)) callback = null;
  900. // If we are not providing a selector or document throw
  901. if(selector == null || typeof selector != 'object') return callback(toError("selector must be a valid JavaScript object"));
  902. if(document == null || typeof document != 'object') return callback(toError("document must be a valid JavaScript object"));
  903. // Get the write concern options
  904. var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options);
  905. // Do we return the actual result document
  906. // Either use override on the function, or go back to default on either the collection
  907. // level or db
  908. finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions;
  909. // Execute the operation
  910. var op = {q: selector, u: document};
  911. op.upsert = options.upsert !== void 0 ? !!options.upsert : false;
  912. op.multi = options.multi !== void 0 ? !!options.multi : false;
  913. // Have we specified collation
  914. decorateWithCollation(finalOptions, self, options);
  915. // Update options
  916. self.s.topology.update(self.s.namespace, [op], finalOptions, function(err, result) {
  917. if(callback == null) return;
  918. if(err) return handleCallback(callback, err, null);
  919. if(result == null) return handleCallback(callback, null, null);
  920. if(result.result.code) return handleCallback(callback, toError(result.result));
  921. if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0]));
  922. // Return the results
  923. handleCallback(callback, null, result);
  924. });
  925. }
  926. /**
  927. * Updates documents.
  928. * @method
  929. * @param {object} selector The selector for the update operation.
  930. * @param {object} document The update document.
  931. * @param {object} [options=null] Optional settings.
  932. * @param {(number|string)} [options.w=null] The write concern.
  933. * @param {number} [options.wtimeout=null] The write concern timeout.
  934. * @param {boolean} [options.j=false] Specify a journal write concern.
  935. * @param {boolean} [options.upsert=false] Update operation is an upsert.
  936. * @param {boolean} [options.multi=false] Update one/all documents with operation.
  937. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  938. * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  939. * @param {Collection~writeOpCallback} [callback] The command result callback
  940. * @throws {MongoError}
  941. * @return {Promise} returns Promise if no callback passed
  942. * @deprecated use updateOne, updateMany or bulkWrite
  943. */
  944. Collection.prototype.update = function(selector, document, options, callback) {
  945. var self = this;
  946. // Add ignoreUndefined
  947. if(this.s.options.ignoreUndefined) {
  948. options = shallowClone(options);
  949. options.ignoreUndefined = this.s.options.ignoreUndefined;
  950. }
  951. // Execute using callback
  952. if(typeof callback == 'function') return updateDocuments(self, selector, document, options, callback);
  953. // Return a Promise
  954. return new this.s.promiseLibrary(function(resolve, reject) {
  955. updateDocuments(self, selector, document, options, function(err, r) {
  956. if(err) return reject(err);
  957. resolve(r);
  958. });
  959. });
  960. }
  961. define.classMethod('update', {callback: true, promise:true});
  962. /**
  963. * @typedef {Object} Collection~deleteWriteOpResult
  964. * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version.
  965. * @property {Number} result.ok Is 1 if the command executed correctly.
  966. * @property {Number} result.n The total count of documents deleted.
  967. * @property {Object} connection The connection object used for the operation.
  968. * @property {Number} deletedCount The number of documents deleted.
  969. */
  970. /**
  971. * The callback format for inserts
  972. * @callback Collection~deleteWriteOpCallback
  973. * @param {MongoError} error An error instance representing the error during the execution.
  974. * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully.
  975. */
  976. /**
  977. * Delete a document on MongoDB
  978. * @method
  979. * @param {object} filter The Filter used to select the document to remove
  980. * @param {object} [options=null] Optional settings.
  981. * @param {(number|string)} [options.w=null] The write concern.
  982. * @param {number} [options.wtimeout=null] The write concern timeout.
  983. * @param {boolean} [options.j=false] Specify a journal write concern.
  984. * @param {Collection~deleteWriteOpCallback} [callback] The command result callback
  985. * @return {Promise} returns Promise if no callback passed
  986. */
  987. Collection.prototype.deleteOne = function(filter, options, callback) {
  988. var self = this;
  989. if(typeof options == 'function') callback = options, options = {};
  990. options = shallowClone(options);
  991. // Add ignoreUndefined
  992. if(this.s.options.ignoreUndefined) {
  993. options = shallowClone(options);
  994. options.ignoreUndefined = this.s.options.ignoreUndefined;
  995. }
  996. // Execute using callback
  997. if(typeof callback == 'function') return deleteOne(self, filter, options, callback);
  998. // Return a Promise
  999. return new this.s.promiseLibrary(function(resolve, reject) {
  1000. deleteOne(self, filter, options, function(err, r) {
  1001. if(err) return reject(err);
  1002. resolve(r);
  1003. });
  1004. });
  1005. }
  1006. var deleteOne = function(self, filter, options, callback) {
  1007. options.single = true;
  1008. removeDocuments(self, filter, options, function(err, r) {
  1009. if(callback == null) return;
  1010. if(err && callback) return callback(err);
  1011. if(r == null) return callback(null, {result: {ok:1}});
  1012. r.deletedCount = r.result.n;
  1013. if(callback) callback(null, r);
  1014. });
  1015. }
  1016. define.classMethod('deleteOne', {callback: true, promise:true});
  1017. Collection.prototype.removeOne = Collection.prototype.deleteOne;
  1018. define.classMethod('removeOne', {callback: true, promise:true});
  1019. /**
  1020. * Delete multiple documents on MongoDB
  1021. * @method
  1022. * @param {object} filter The Filter used to select the documents to remove
  1023. * @param {object} [options=null] Optional settings.
  1024. * @param {(number|string)} [options.w=null] The write concern.
  1025. * @param {number} [options.wtimeout=null] The write concern timeout.
  1026. * @param {boolean} [options.j=false] Specify a journal write concern.
  1027. * @param {Collection~deleteWriteOpCallback} [callback] The command result callback
  1028. * @return {Promise} returns Promise if no callback passed
  1029. */
  1030. Collection.prototype.deleteMany = function(filter, options, callback) {
  1031. var self = this;
  1032. if(typeof options == 'function') callback = options, options = {};
  1033. options = shallowClone(options);
  1034. // Add ignoreUndefined
  1035. if(this.s.options.ignoreUndefined) {
  1036. options = shallowClone(options);
  1037. options.ignoreUndefined = this.s.options.ignoreUndefined;
  1038. }
  1039. // Execute using callback
  1040. if(typeof callback == 'function') return deleteMany(self, filter, options, callback);
  1041. // Return a Promise
  1042. return new this.s.promiseLibrary(function(resolve, reject) {
  1043. deleteMany(self, filter, options, function(err, r) {
  1044. if(err) return reject(err);
  1045. resolve(r);
  1046. });
  1047. });
  1048. }
  1049. var deleteMany = function(self, filter, options, callback) {
  1050. options.single = false;
  1051. removeDocuments(self, filter, options, function(err, r) {
  1052. if(callback == null) return;
  1053. if(err && callback) return callback(err);
  1054. if(r == null) return callback(null, {result: {ok:1}});
  1055. r.deletedCount = r.result.n;
  1056. if(callback) callback(null, r);
  1057. });
  1058. }
  1059. var removeDocuments = function(self, selector, options, callback) {
  1060. if(typeof options == 'function') {
  1061. callback = options, options = {};
  1062. } else if (typeof selector === 'function') {
  1063. callback = selector;
  1064. options = {};
  1065. selector = {};
  1066. }
  1067. // Create an empty options object if the provided one is null
  1068. options = options || {};
  1069. // Get the write concern options
  1070. var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options);
  1071. // If selector is null set empty
  1072. if(selector == null) selector = {};
  1073. // Build the op
  1074. var op = {q: selector, limit: 0};
  1075. if(options.single) op.limit = 1;
  1076. // Have we specified collation
  1077. decorateWithCollation(finalOptions, self, options);
  1078. // Execute the remove
  1079. self.s.topology.remove(self.s.namespace, [op], finalOptions, function(err, result) {
  1080. if(callback == null) return;
  1081. if(err) return handleCallback(callback, err, null);
  1082. if(result == null) return handleCallback(callback, null, null);
  1083. if(result.result.code) return handleCallback(callback, toError(result.result));
  1084. if(result.result.writeErrors) return handleCallback(callback, toError(result.result.writeErrors[0]));
  1085. // Return the results
  1086. handleCallback(callback, null, result);
  1087. });
  1088. }
  1089. define.classMethod('deleteMany', {callback: true, promise:true});
  1090. Collection.prototype.removeMany = Collection.prototype.deleteMany;
  1091. define.classMethod('removeMany', {callback: true, promise:true});
  1092. /**
  1093. * Remove documents.
  1094. * @method
  1095. * @param {object} selector The selector for the update operation.
  1096. * @param {object} [options=null] Optional settings.
  1097. * @param {(number|string)} [options.w=null] The write concern.
  1098. * @param {number} [options.wtimeout=null] The write concern timeout.
  1099. * @param {boolean} [options.j=false] Specify a journal write concern.
  1100. * @param {boolean} [options.single=false] Removes the first document found.
  1101. * @param {Collection~writeOpCallback} [callback] The command result callback
  1102. * @return {Promise} returns Promise if no callback passed
  1103. * @deprecated use deleteOne, deleteMany or bulkWrite
  1104. */
  1105. Collection.prototype.remove = function(selector, options, callback) {
  1106. var self = this;
  1107. // Add ignoreUndefined
  1108. if(this.s.options.ignoreUndefined) {
  1109. options = shallowClone(options);
  1110. options.ignoreUndefined = this.s.options.ignoreUndefined;
  1111. }
  1112. // Execute using callback
  1113. if(typeof callback == 'function') return removeDocuments(self, selector, options, callback);
  1114. // Return a Promise
  1115. return new this.s.promiseLibrary(function(resolve, reject) {
  1116. removeDocuments(self, selector, options, function(err, r) {
  1117. if(err) return reject(err);
  1118. resolve(r);
  1119. });
  1120. });
  1121. }
  1122. define.classMethod('remove', {callback: true, promise:true});
  1123. /**
  1124. * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic
  1125. * operators and update instead for more efficient operations.
  1126. * @method
  1127. * @param {object} doc Document to save
  1128. * @param {object} [options=null] Optional settings.
  1129. * @param {(number|string)} [options.w=null] The write concern.
  1130. * @param {number} [options.wtimeout=null] The write concern timeout.
  1131. * @param {boolean} [options.j=false] Specify a journal write concern.
  1132. * @param {Collection~writeOpCallback} [callback] The command result callback
  1133. * @return {Promise} returns Promise if no callback passed
  1134. * @deprecated use insertOne, insertMany, updateOne or updateMany
  1135. */
  1136. Collection.prototype.save = function(doc, options, callback) {
  1137. var self = this;
  1138. if(typeof options == 'function') callback = options, options = {};
  1139. options = options || {};
  1140. // Add ignoreUndefined
  1141. if(this.s.options.ignoreUndefined) {
  1142. options = shallowClone(options);
  1143. options.ignoreUndefined = this.s.options.ignoreUndefined;
  1144. }
  1145. // Execute using callback
  1146. if(typeof callback == 'function') return save(self, doc, options, callback);
  1147. // Return a Promise
  1148. return new this.s.promiseLibrary(function(resolve, reject) {
  1149. save(self, doc, options, function(err, r) {
  1150. if(err) return reject(err);
  1151. resolve(r);
  1152. });
  1153. });
  1154. }
  1155. var save = function(self, doc, options, callback) {
  1156. // Get the write concern options
  1157. var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options);
  1158. // Establish if we need to perform an insert or update
  1159. if(doc._id != null) {
  1160. finalOptions.upsert = true;
  1161. return updateDocuments(self, {_id: doc._id}, doc, finalOptions, callback);
  1162. }
  1163. // Insert the document
  1164. insertDocuments(self, [doc], options, function(err, r) {
  1165. if(callback == null) return;
  1166. if(doc == null) return handleCallback(callback, null, null);
  1167. if(err) return handleCallback(callback, err, null);
  1168. handleCallback(callback, null, r);
  1169. });
  1170. }
  1171. define.classMethod('save', {callback: true, promise:true});
  1172. /**
  1173. * The callback format for results
  1174. * @callback Collection~resultCallback
  1175. * @param {MongoError} error An error instance representing the error during the execution.
  1176. * @param {object} result The result object if the command was executed successfully.
  1177. */
  1178. /**
  1179. * Fetches the first document that matches the query
  1180. * @method
  1181. * @param {object} query Query for find Operation
  1182. * @param {object} [options=null] Optional settings.
  1183. * @param {number} [options.limit=0] Sets the limit of documents returned in the query.
  1184. * @param {(array|object)} [options.sort=null] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.
  1185. * @param {object} [options.fields=null] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1}
  1186. * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination).
  1187. * @param {Object} [options.hint=null] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1}
  1188. * @param {boolean} [options.explain=false] Explain the query instead of returning the data.
  1189. * @param {boolean} [options.snapshot=false] Snapshot query.
  1190. * @param {boolean} [options.timeout=false] Specify if the cursor can timeout.
  1191. * @param {boolean} [options.tailable=false] Specify if the cursor is tailable.
  1192. * @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results.
  1193. * @param {boolean} [options.returnKey=false] Only return the index key.
  1194. * @param {number} [options.maxScan=null] Limit the number of items to scan.
  1195. * @param {number} [options.min=null] Set index bounds.
  1196. * @param {number} [options.max=null] Set index bounds.
  1197. * @param {boolean} [options.showDiskLoc=false] Show disk location of results.
  1198. * @param {string} [options.comment=null] You can put a $comment field on a query to make looking in the profiler logs simpler.
  1199. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
  1200. * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.
  1201. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
  1202. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
  1203. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1204. * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system
  1205. * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query.
  1206. * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  1207. * @param {Collection~resultCallback} [callback] The command result callback
  1208. * @return {Promise} returns Promise if no callback passed
  1209. */
  1210. Collection.prototype.findOne = function() {
  1211. var self = this;
  1212. var args = Array.prototype.slice.call(arguments, 0);
  1213. var callback = args.pop();
  1214. if(typeof callback != 'function') args.push(callback);
  1215. // Execute using callback
  1216. if(typeof callback == 'function') return findOne(self, args, callback);
  1217. // Return a Promise
  1218. return new this.s.promiseLibrary(function(resolve, reject) {
  1219. findOne(self, args, function(err, r) {
  1220. if(err) return reject(err);
  1221. resolve(r);
  1222. });
  1223. });
  1224. }
  1225. var findOne = function(self, args, callback) {
  1226. var cursor = self.find.apply(self, args).limit(-1).batchSize(1);
  1227. // Return the item
  1228. cursor.next(function(err, item) {
  1229. if(err != null) return handleCallback(callback, toError(err), null);
  1230. handleCallback(callback, null, item);
  1231. });
  1232. }
  1233. define.classMethod('findOne', {callback: true, promise:true});
  1234. /**
  1235. * The callback format for the collection method, must be used if strict is specified
  1236. * @callback Collection~collectionResultCallback
  1237. * @param {MongoError} error An error instance representing the error during the execution.
  1238. * @param {Collection} collection The collection instance.
  1239. */
  1240. /**
  1241. * Rename the collection.
  1242. *
  1243. * @method
  1244. * @param {string} newName New name of of the collection.
  1245. * @param {object} [options=null] Optional settings.
  1246. * @param {boolean} [options.dropTarget=false] Drop the target name collection if it previously exists.
  1247. * @param {Collection~collectionResultCallback} [callback] The results callback
  1248. * @return {Promise} returns Promise if no callback passed
  1249. */
  1250. Collection.prototype.rename = function(newName, opt, callback) {
  1251. var self = this;
  1252. if(typeof opt == 'function') callback = opt, opt = {};
  1253. opt = assign({}, opt, {readPreference: ReadPreference.PRIMARY});
  1254. // Execute using callback
  1255. if(typeof callback == 'function') return rename(self, newName, opt, callback);
  1256. // Return a Promise
  1257. return new this.s.promiseLibrary(function(resolve, reject) {
  1258. rename(self, newName, opt, function(err, r) {
  1259. if(err) return reject(err);
  1260. resolve(r);
  1261. });
  1262. });
  1263. }
  1264. var rename = function(self, newName, opt, callback) {
  1265. // Check the collection name
  1266. checkCollectionName(newName);
  1267. // Build the command
  1268. var renameCollection = f("%s.%s", self.s.dbName, self.s.name);
  1269. var toCollection = f("%s.%s", self.s.dbName, newName);
  1270. var dropTarget = typeof opt.dropTarget == 'boolean' ? opt.dropTarget : false;
  1271. var cmd = {'renameCollection':renameCollection, 'to':toCollection, 'dropTarget':dropTarget};
  1272. // Decorate command with writeConcern if supported
  1273. decorateWithWriteConcern(cmd, self, opt);
  1274. // Execute against admin
  1275. self.s.db.admin().command(cmd, opt, function(err, doc) {
  1276. if(err) return handleCallback(callback, err, null);
  1277. // We have an error
  1278. if(doc.errmsg) return handleCallback(callback, toError(doc), null);
  1279. try {
  1280. return handleCallback(callback, null, new Collection(self.s.db, self.s.topology, self.s.dbName, newName, self.s.pkFactory, self.s.options));
  1281. } catch(err) {
  1282. return handleCallback(callback, toError(err), null);
  1283. }
  1284. });
  1285. }
  1286. define.classMethod('rename', {callback: true, promise:true});
  1287. /**
  1288. * Drop the collection from the database, removing it permanently. New accesses will create a new collection.
  1289. *
  1290. * @method
  1291. * @param {object} [options=null] Optional settings.
  1292. * @param {Collection~resultCallback} [callback] The results callback
  1293. * @return {Promise} returns Promise if no callback passed
  1294. */
  1295. Collection.prototype.drop = function(options, callback) {
  1296. var self = this;
  1297. if(typeof options == 'function') callback = options, options = {};
  1298. options = options || {};
  1299. // Execute using callback
  1300. if(typeof callback == 'function') return self.s.db.dropCollection(self.s.name, options, callback);
  1301. // Return a Promise
  1302. return new this.s.promiseLibrary(function(resolve, reject) {
  1303. self.s.db.dropCollection(self.s.name, options, function(err, r) {
  1304. if(err) return reject(err);
  1305. resolve(r);
  1306. });
  1307. });
  1308. }
  1309. define.classMethod('drop', {callback: true, promise:true});
  1310. /**
  1311. * Returns the options of the collection.
  1312. *
  1313. * @method
  1314. * @param {Collection~resultCallback} [callback] The results callback
  1315. * @return {Promise} returns Promise if no callback passed
  1316. */
  1317. Collection.prototype.options = function(callback) {
  1318. var self = this;
  1319. // Execute using callback
  1320. if(typeof callback == 'function') return options(self, callback);
  1321. // Return a Promise
  1322. return new this.s.promiseLibrary(function(resolve, reject) {
  1323. options(self, function(err, r) {
  1324. if(err) return reject(err);
  1325. resolve(r);
  1326. });
  1327. });
  1328. }
  1329. var options = function(self, callback) {
  1330. self.s.db.listCollections({name: self.s.name}).toArray(function(err, collections) {
  1331. if(err) return handleCallback(callback, err);
  1332. if(collections.length == 0) {
  1333. return handleCallback(callback, MongoError.create({message: f("collection %s not found", self.s.namespace), driver:true }));
  1334. }
  1335. handleCallback(callback, err, collections[0].options || null);
  1336. });
  1337. }
  1338. define.classMethod('options', {callback: true, promise:true});
  1339. /**
  1340. * Returns if the collection is a capped collection
  1341. *
  1342. * @method
  1343. * @param {Collection~resultCallback} [callback] The results callback
  1344. * @return {Promise} returns Promise if no callback passed
  1345. */
  1346. Collection.prototype.isCapped = function(callback) {
  1347. var self = this;
  1348. // Execute using callback
  1349. if(typeof callback == 'function') return isCapped(self, callback);
  1350. // Return a Promise
  1351. return new this.s.promiseLibrary(function(resolve, reject) {
  1352. isCapped(self, function(err, r) {
  1353. if(err) return reject(err);
  1354. resolve(r);
  1355. });
  1356. });
  1357. }
  1358. var isCapped = function(self, callback) {
  1359. self.options(function(err, document) {
  1360. if(err) return handleCallback(callback, err);
  1361. handleCallback(callback, null, document && document.capped);
  1362. });
  1363. }
  1364. define.classMethod('isCapped', {callback: true, promise:true});
  1365. /**
  1366. * Creates an index on the db and collection collection.
  1367. * @method
  1368. * @param {(string|object)} fieldOrSpec Defines the index.
  1369. * @param {object} [options=null] Optional settings.
  1370. * @param {(number|string)} [options.w=null] The write concern.
  1371. * @param {number} [options.wtimeout=null] The write concern timeout.
  1372. * @param {boolean} [options.j=false] Specify a journal write concern.
  1373. * @param {boolean} [options.unique=false] Creates an unique index.
  1374. * @param {boolean} [options.sparse=false] Creates a sparse index.
  1375. * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.
  1376. * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
  1377. * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates.
  1378. * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates.
  1379. * @param {number} [options.v=null] Specify the format version of the indexes.
  1380. * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
  1381. * @param {string} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
  1382. * @param {object} [options.partialFilterExpression=null] Creates a partial index based on the given filter object (MongoDB 3.2 or higher)
  1383. * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  1384. * @param {Collection~resultCallback} [callback] The command result callback
  1385. * @return {Promise} returns Promise if no callback passed
  1386. */
  1387. Collection.prototype.createIndex = function(fieldOrSpec, options, callback) {
  1388. var self = this;
  1389. var args = Array.prototype.slice.call(arguments, 1);
  1390. callback = args.pop();
  1391. if(typeof callback != 'function') args.push(callback);
  1392. options = args.length ? args.shift() || {} : {};
  1393. options = typeof callback === 'function' ? options : callback;
  1394. options = options == null ? {} : options;
  1395. // Execute using callback
  1396. if(typeof callback == 'function') return createIndex(self, fieldOrSpec, options, callback);
  1397. // Return a Promise
  1398. return new this.s.promiseLibrary(function(resolve, reject) {
  1399. createIndex(self, fieldOrSpec, options, function(err, r) {
  1400. if(err) return reject(err);
  1401. resolve(r);
  1402. });
  1403. });
  1404. }
  1405. var createIndex = function(self, fieldOrSpec, options, callback) {
  1406. self.s.db.createIndex(self.s.name, fieldOrSpec, options, callback);
  1407. }
  1408. define.classMethod('createIndex', {callback: true, promise:true});
  1409. /**
  1410. * Creates multiple indexes in the collection, this method is only supported for
  1411. * MongoDB 2.6 or higher. Earlier version of MongoDB will throw a command not supported
  1412. * error. Index specifications are defined at https://www.mongodb.com/docs/manual/reference/command/createIndexes/.
  1413. * @method
  1414. * @param {array} indexSpecs An array of index specifications to be created
  1415. * @param {Collection~resultCallback} [callback] The command result callback
  1416. * @return {Promise} returns Promise if no callback passed
  1417. */
  1418. Collection.prototype.createIndexes = function(indexSpecs, callback) {
  1419. var self = this;
  1420. // Execute using callback
  1421. if(typeof callback == 'function') return createIndexes(self, indexSpecs, callback);
  1422. // Return a Promise
  1423. return new this.s.promiseLibrary(function(resolve, reject) {
  1424. createIndexes(self, indexSpecs, function(err, r) {
  1425. if(err) return reject(err);
  1426. resolve(r);
  1427. });
  1428. });
  1429. }
  1430. var createIndexes = function(self, indexSpecs, callback) {
  1431. var capabilities = self.s.topology.capabilities();
  1432. // Ensure we generate the correct name if the parameter is not set
  1433. for(var i = 0; i < indexSpecs.length; i++) {
  1434. if(indexSpecs[i].name == null) {
  1435. var keys = [];
  1436. // Did the user pass in a collation, check if our write server supports it
  1437. if(indexSpecs[i].collation && capabilities && !capabilities.commandsTakeCollation) {
  1438. return callback(new MongoError(f('server/primary/mongos does not support collation')));
  1439. }
  1440. for(var name in indexSpecs[i].key) {
  1441. keys.push(f('%s_%s', name, indexSpecs[i].key[name]));
  1442. }
  1443. // Set the name
  1444. indexSpecs[i].name = keys.join('_');
  1445. }
  1446. }
  1447. // Execute the index
  1448. self.s.db.command({
  1449. createIndexes: self.s.name, indexes: indexSpecs
  1450. }, { readPreference: ReadPreference.PRIMARY }, callback);
  1451. }
  1452. define.classMethod('createIndexes', {callback: true, promise:true});
  1453. /**
  1454. * Drops an index from this collection.
  1455. * @method
  1456. * @param {string} indexName Name of the index to drop.
  1457. * @param {object} [options=null] Optional settings.
  1458. * @param {(number|string)} [options.w=null] The write concern.
  1459. * @param {number} [options.wtimeout=null] The write concern timeout.
  1460. * @param {boolean} [options.j=false] Specify a journal write concern.
  1461. * @param {Collection~resultCallback} [callback] The command result callback
  1462. * @return {Promise} returns Promise if no callback passed
  1463. */
  1464. Collection.prototype.dropIndex = function(indexName, options, callback) {
  1465. var self = this;
  1466. var args = Array.prototype.slice.call(arguments, 1);
  1467. callback = args.pop();
  1468. if(typeof callback != 'function') args.push(callback);
  1469. options = args.length ? args.shift() || {} : {};
  1470. // Run only against primary
  1471. options.readPreference = ReadPreference.PRIMARY;
  1472. // Execute using callback
  1473. if(typeof callback == 'function') return dropIndex(self, indexName, options, callback);
  1474. // Return a Promise
  1475. return new this.s.promiseLibrary(function(resolve, reject) {
  1476. dropIndex(self, indexName, options, function(err, r) {
  1477. if(err) return reject(err);
  1478. resolve(r);
  1479. });
  1480. });
  1481. }
  1482. var dropIndex = function(self, indexName, options, callback) {
  1483. // Delete index command
  1484. var cmd = {'dropIndexes':self.s.name, 'index':indexName};
  1485. // Decorate command with writeConcern if supported
  1486. decorateWithWriteConcern(cmd, self, options);
  1487. // Execute command
  1488. self.s.db.command(cmd, options, function(err, result) {
  1489. if(typeof callback != 'function') return;
  1490. if(err) return handleCallback(callback, err, null);
  1491. handleCallback(callback, null, result);
  1492. });
  1493. }
  1494. define.classMethod('dropIndex', {callback: true, promise:true});
  1495. /**
  1496. * Drops all indexes from this collection.
  1497. * @method
  1498. * @param {Collection~resultCallback} [callback] The command result callback
  1499. * @return {Promise} returns Promise if no callback passed
  1500. */
  1501. Collection.prototype.dropIndexes = function(options, callback) {
  1502. var self = this;
  1503. // Do we have options
  1504. if(typeof options == 'function') callback = options, options = {};
  1505. options = options || {};
  1506. // Execute using callback
  1507. if(typeof callback == 'function') return dropIndexes(self, options, callback);
  1508. // Return a Promise
  1509. return new this.s.promiseLibrary(function(resolve, reject) {
  1510. dropIndexes(self, function(err, r) {
  1511. if(err) return reject(err);
  1512. resolve(r);
  1513. });
  1514. });
  1515. }
  1516. var dropIndexes = function(self, options, callback) {
  1517. self.dropIndex('*', options, function(err) {
  1518. if(err) return handleCallback(callback, err, false);
  1519. handleCallback(callback, null, true);
  1520. });
  1521. }
  1522. define.classMethod('dropIndexes', {callback: true, promise:true});
  1523. /**
  1524. * Drops all indexes from this collection.
  1525. * @method
  1526. * @deprecated use dropIndexes
  1527. * @param {Collection~resultCallback} callback The command result callback
  1528. * @return {Promise} returns Promise if no [callback] passed
  1529. */
  1530. Collection.prototype.dropAllIndexes = Collection.prototype.dropIndexes;
  1531. define.classMethod('dropAllIndexes', {callback: true, promise:true});
  1532. /**
  1533. * Reindex all indexes on the collection
  1534. * Warning: reIndex is a blocking operation (indexes are rebuilt in the foreground) and will be slow for large collections.
  1535. * @method
  1536. * @param {Collection~resultCallback} [callback] The command result callback
  1537. * @return {Promise} returns Promise if no callback passed
  1538. */
  1539. Collection.prototype.reIndex = function(options, callback) {
  1540. var self = this;
  1541. if(typeof options == 'function') callback = options, options = {};
  1542. options = options || {};
  1543. // Execute using callback
  1544. if(typeof callback == 'function') return reIndex(self, options, callback);
  1545. // Return a Promise
  1546. return new this.s.promiseLibrary(function(resolve, reject) {
  1547. reIndex(self, options, function(err, r) {
  1548. if(err) return reject(err);
  1549. resolve(r);
  1550. });
  1551. });
  1552. }
  1553. var reIndex = function(self, options, callback) {
  1554. // Reindex
  1555. var cmd = {'reIndex':self.s.name};
  1556. // Execute the command
  1557. self.s.db.command(cmd, options, function(err, result) {
  1558. if(callback == null) return;
  1559. if(err) return handleCallback(callback, err, null);
  1560. handleCallback(callback, null, result.ok ? true : false);
  1561. });
  1562. }
  1563. define.classMethod('reIndex', {callback: true, promise:true});
  1564. /**
  1565. * Get the list of all indexes information for the collection.
  1566. *
  1567. * @method
  1568. * @param {object} [options=null] Optional settings.
  1569. * @param {number} [options.batchSize=null] The batchSize for the returned command cursor or if pre 2.8 the systems batch collection
  1570. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1571. * @return {CommandCursor}
  1572. */
  1573. Collection.prototype.listIndexes = function(options) {
  1574. options = options || {};
  1575. // Clone the options
  1576. options = shallowClone(options);
  1577. // Determine the read preference in the options.
  1578. options = getReadPreference(this, options, this.s.db, this);
  1579. // Set the CommandCursor constructor
  1580. options.cursorFactory = CommandCursor;
  1581. // Set the promiseLibrary
  1582. options.promiseLibrary = this.s.promiseLibrary;
  1583. if(!this.s.topology.capabilities()) {
  1584. throw new MongoError('cannot connect to server');
  1585. }
  1586. // We have a list collections command
  1587. if(this.s.topology.capabilities().hasListIndexesCommand) {
  1588. // Cursor options
  1589. var cursor = options.batchSize ? {batchSize: options.batchSize} : {}
  1590. // Build the command
  1591. var command = { listIndexes: this.s.name, cursor: cursor };
  1592. // Execute the cursor
  1593. cursor = this.s.topology.cursor(f('%s.$cmd', this.s.dbName), command, options);
  1594. // Do we have a readPreference, apply it
  1595. if(options.readPreference) cursor.setReadPreference(options.readPreference);
  1596. // Return the cursor
  1597. return cursor;
  1598. }
  1599. // Get the namespace
  1600. var ns = f('%s.system.indexes', this.s.dbName);
  1601. // Get the query
  1602. cursor = this.s.topology.cursor(ns, {find: ns, query: {ns: this.s.namespace}}, options);
  1603. // Do we have a readPreference, apply it
  1604. if(options.readPreference) cursor.setReadPreference(options.readPreference);
  1605. // Set the passed in batch size if one was provided
  1606. if(options.batchSize) cursor = cursor.batchSize(options.batchSize);
  1607. // Return the cursor
  1608. return cursor;
  1609. };
  1610. define.classMethod('listIndexes', {callback: false, promise:false, returns: [CommandCursor]});
  1611. /**
  1612. * Ensures that an index exists, if it does not it creates it
  1613. * @method
  1614. * @deprecated use createIndexes instead
  1615. * @param {(string|object)} fieldOrSpec Defines the index.
  1616. * @param {object} [options=null] Optional settings.
  1617. * @param {(number|string)} [options.w=null] The write concern.
  1618. * @param {number} [options.wtimeout=null] The write concern timeout.
  1619. * @param {boolean} [options.j=false] Specify a journal write concern.
  1620. * @param {boolean} [options.unique=false] Creates an unique index.
  1621. * @param {boolean} [options.sparse=false] Creates a sparse index.
  1622. * @param {boolean} [options.background=false] Creates the index in the background, yielding whenever possible.
  1623. * @param {boolean} [options.dropDups=false] A unique index cannot be created on a key that has pre-existing duplicate values. If you would like to create the index anyway, keeping the first document the database indexes and deleting all subsequent documents that have duplicate value
  1624. * @param {number} [options.min=null] For geospatial indexes set the lower bound for the co-ordinates.
  1625. * @param {number} [options.max=null] For geospatial indexes set the high bound for the co-ordinates.
  1626. * @param {number} [options.v=null] Specify the format version of the indexes.
  1627. * @param {number} [options.expireAfterSeconds=null] Allows you to expire data on indexes applied to a data (MongoDB 2.2 or higher)
  1628. * @param {number} [options.name=null] Override the autogenerated index name (useful if the resulting name is larger than 128 bytes)
  1629. * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  1630. * @param {Collection~resultCallback} [callback] The command result callback
  1631. * @return {Promise} returns Promise if no callback passed
  1632. */
  1633. Collection.prototype.ensureIndex = function(fieldOrSpec, options, callback) {
  1634. var self = this;
  1635. if(typeof options == 'function') callback = options, options = {};
  1636. options = options || {};
  1637. // Execute using callback
  1638. if(typeof callback == 'function') return ensureIndex(self, fieldOrSpec, options, callback);
  1639. // Return a Promise
  1640. return new this.s.promiseLibrary(function(resolve, reject) {
  1641. ensureIndex(self, fieldOrSpec, options, function(err, r) {
  1642. if(err) return reject(err);
  1643. resolve(r);
  1644. });
  1645. });
  1646. }
  1647. var ensureIndex = function(self, fieldOrSpec, options, callback) {
  1648. self.s.db.ensureIndex(self.s.name, fieldOrSpec, options, callback);
  1649. }
  1650. define.classMethod('ensureIndex', {callback: true, promise:true});
  1651. /**
  1652. * Checks if one or more indexes exist on the collection, fails on first non-existing index
  1653. * @method
  1654. * @param {(string|array)} indexes One or more index names to check.
  1655. * @param {Collection~resultCallback} [callback] The command result callback
  1656. * @return {Promise} returns Promise if no callback passed
  1657. */
  1658. Collection.prototype.indexExists = function(indexes, callback) {
  1659. var self = this;
  1660. // Execute using callback
  1661. if(typeof callback == 'function') return indexExists(self, indexes, callback);
  1662. // Return a Promise
  1663. return new this.s.promiseLibrary(function(resolve, reject) {
  1664. indexExists(self, indexes, function(err, r) {
  1665. if(err) return reject(err);
  1666. resolve(r);
  1667. });
  1668. });
  1669. }
  1670. var indexExists = function(self, indexes, callback) {
  1671. self.indexInformation(function(err, indexInformation) {
  1672. // If we have an error return
  1673. if(err != null) return handleCallback(callback, err, null);
  1674. // Let's check for the index names
  1675. if(!Array.isArray(indexes)) return handleCallback(callback, null, indexInformation[indexes] != null);
  1676. // Check in list of indexes
  1677. for(var i = 0; i < indexes.length; i++) {
  1678. if(indexInformation[indexes[i]] == null) {
  1679. return handleCallback(callback, null, false);
  1680. }
  1681. }
  1682. // All keys found return true
  1683. return handleCallback(callback, null, true);
  1684. });
  1685. }
  1686. define.classMethod('indexExists', {callback: true, promise:true});
  1687. /**
  1688. * Retrieves this collections index info.
  1689. * @method
  1690. * @param {object} [options=null] Optional settings.
  1691. * @param {boolean} [options.full=false] Returns the full raw index information.
  1692. * @param {Collection~resultCallback} [callback] The command result callback
  1693. * @return {Promise} returns Promise if no callback passed
  1694. */
  1695. Collection.prototype.indexInformation = function(options, callback) {
  1696. var self = this;
  1697. // Unpack calls
  1698. var args = Array.prototype.slice.call(arguments, 0);
  1699. callback = args.pop();
  1700. if(typeof callback != 'function') args.push(callback);
  1701. options = args.length ? args.shift() || {} : {};
  1702. // Execute using callback
  1703. if(typeof callback == 'function') return indexInformation(self, options, callback);
  1704. // Return a Promise
  1705. return new this.s.promiseLibrary(function(resolve, reject) {
  1706. indexInformation(self, options, function(err, r) {
  1707. if(err) return reject(err);
  1708. resolve(r);
  1709. });
  1710. });
  1711. }
  1712. var indexInformation = function(self, options, callback) {
  1713. self.s.db.indexInformation(self.s.name, options, callback);
  1714. }
  1715. define.classMethod('indexInformation', {callback: true, promise:true});
  1716. /**
  1717. * The callback format for results
  1718. * @callback Collection~countCallback
  1719. * @param {MongoError} error An error instance representing the error during the execution.
  1720. * @param {number} result The count of documents that matched the query.
  1721. */
  1722. /**
  1723. * Count number of matching documents in the db to a query.
  1724. * @method
  1725. * @param {object} query The query for the count.
  1726. * @param {object} [options=null] Optional settings.
  1727. * @param {boolean} [options.limit=null] The limit of documents to count.
  1728. * @param {boolean} [options.skip=null] The number of documents to skip for the count.
  1729. * @param {string} [options.hint=null] An index name hint for the query.
  1730. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1731. * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query.
  1732. * @param {Collection~countCallback} [callback] The command result callback
  1733. * @return {Promise} returns Promise if no callback passed
  1734. */
  1735. Collection.prototype.count = function(query, options, callback) {
  1736. var self = this;
  1737. var args = Array.prototype.slice.call(arguments, 0);
  1738. callback = args.pop();
  1739. if(typeof callback != 'function') args.push(callback);
  1740. var queryOption = args.length ? args.shift() || {} : {};
  1741. var optionsOption = args.length ? args.shift() || {} : {};
  1742. // Execute using callback
  1743. if(typeof callback == 'function') return count(self, queryOption, optionsOption, callback);
  1744. // Check if query is empty
  1745. query = query || {};
  1746. options = options || {};
  1747. // Return a Promise
  1748. return new this.s.promiseLibrary(function(resolve, reject) {
  1749. count(self, query, options, function(err, r) {
  1750. if(err) return reject(err);
  1751. resolve(r);
  1752. });
  1753. });
  1754. };
  1755. var count = function(self, query, options, callback) {
  1756. var skip = options.skip;
  1757. var limit = options.limit;
  1758. var hint = options.hint;
  1759. var maxTimeMS = options.maxTimeMS;
  1760. // Final query
  1761. var cmd = {
  1762. 'count': self.s.name, 'query': query
  1763. };
  1764. // Add limit, skip and maxTimeMS if defined
  1765. if(typeof skip == 'number') cmd.skip = skip;
  1766. if(typeof limit == 'number') cmd.limit = limit;
  1767. if(typeof maxTimeMS == 'number') cmd.maxTimeMS = maxTimeMS;
  1768. if(hint) cmd.hint = hint;
  1769. options = shallowClone(options);
  1770. // Ensure we have the right read preference inheritance
  1771. options = getReadPreference(self, options, self.s.db, self);
  1772. // Do we have a readConcern specified
  1773. if(self.s.readConcern) {
  1774. cmd.readConcern = self.s.readConcern;
  1775. }
  1776. // Have we specified collation
  1777. decorateWithCollation(cmd, self, options);
  1778. // Execute command
  1779. self.s.db.command(cmd, options, function(err, result) {
  1780. if(err) return handleCallback(callback, err);
  1781. handleCallback(callback, null, result.n);
  1782. });
  1783. }
  1784. define.classMethod('count', {callback: true, promise:true});
  1785. /**
  1786. * The distinct command returns returns a list of distinct values for the given key across a collection.
  1787. * @method
  1788. * @param {string} key Field of the document to find distinct values for.
  1789. * @param {object} query The query for filtering the set of documents to which we apply the distinct filter.
  1790. * @param {object} [options=null] Optional settings.
  1791. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  1792. * @param {number} [options.maxTimeMS=null] Number of milliseconds to wait before aborting the query.
  1793. * @param {Collection~resultCallback} [callback] The command result callback
  1794. * @return {Promise} returns Promise if no callback passed
  1795. */
  1796. Collection.prototype.distinct = function(key, query, options, callback) {
  1797. var self = this;
  1798. var args = Array.prototype.slice.call(arguments, 1);
  1799. callback = args.pop();
  1800. if(typeof callback != 'function') args.push(callback);
  1801. var queryOption = args.length ? args.shift() || {} : {};
  1802. var optionsOption = args.length ? args.shift() || {} : {};
  1803. // Execute using callback
  1804. if(typeof callback == 'function') return distinct(self, key, queryOption, optionsOption, callback);
  1805. // Ensure the query and options are set
  1806. query = query || {};
  1807. options = options || {};
  1808. // Return a Promise
  1809. return new this.s.promiseLibrary(function(resolve, reject) {
  1810. distinct(self, key, query, options, function(err, r) {
  1811. if(err) return reject(err);
  1812. resolve(r);
  1813. });
  1814. });
  1815. };
  1816. var distinct = function(self, key, query, options, callback) {
  1817. // maxTimeMS option
  1818. var maxTimeMS = options.maxTimeMS;
  1819. // Distinct command
  1820. var cmd = {
  1821. 'distinct': self.s.name, 'key': key, 'query': query
  1822. };
  1823. options = shallowClone(options);
  1824. // Ensure we have the right read preference inheritance
  1825. options = getReadPreference(self, options, self.s.db, self);
  1826. // Add maxTimeMS if defined
  1827. if(typeof maxTimeMS == 'number')
  1828. cmd.maxTimeMS = maxTimeMS;
  1829. // Do we have a readConcern specified
  1830. if(self.s.readConcern) {
  1831. cmd.readConcern = self.s.readConcern;
  1832. }
  1833. // Have we specified collation
  1834. decorateWithCollation(cmd, self, options);
  1835. // Execute the command
  1836. self.s.db.command(cmd, options, function(err, result) {
  1837. if(err) return handleCallback(callback, err);
  1838. handleCallback(callback, null, result.values);
  1839. });
  1840. }
  1841. define.classMethod('distinct', {callback: true, promise:true});
  1842. /**
  1843. * Retrieve all the indexes on the collection.
  1844. * @method
  1845. * @param {Collection~resultCallback} [callback] The command result callback
  1846. * @return {Promise} returns Promise if no callback passed
  1847. */
  1848. Collection.prototype.indexes = function(callback) {
  1849. var self = this;
  1850. // Execute using callback
  1851. if(typeof callback == 'function') return indexes(self, callback);
  1852. // Return a Promise
  1853. return new this.s.promiseLibrary(function(resolve, reject) {
  1854. indexes(self, function(err, r) {
  1855. if(err) return reject(err);
  1856. resolve(r);
  1857. });
  1858. });
  1859. }
  1860. var indexes = function(self, callback) {
  1861. self.s.db.indexInformation(self.s.name, {full:true}, callback);
  1862. }
  1863. define.classMethod('indexes', {callback: true, promise:true});
  1864. /**
  1865. * Get all the collection statistics.
  1866. *
  1867. * @method
  1868. * @param {object} [options=null] Optional settings.
  1869. * @param {number} [options.scale=null] Divide the returned sizes by scale value.
  1870. * @param {Collection~resultCallback} [callback] The collection result callback
  1871. * @return {Promise} returns Promise if no callback passed
  1872. */
  1873. Collection.prototype.stats = function(options, callback) {
  1874. var self = this;
  1875. var args = Array.prototype.slice.call(arguments, 0);
  1876. callback = args.pop();
  1877. if(typeof callback != 'function') args.push(callback);
  1878. // Fetch all commands
  1879. options = args.length ? args.shift() || {} : {};
  1880. // Execute using callback
  1881. if(typeof callback == 'function') return stats(self, options, callback);
  1882. // Return a Promise
  1883. return new this.s.promiseLibrary(function(resolve, reject) {
  1884. stats(self, options, function(err, r) {
  1885. if(err) return reject(err);
  1886. resolve(r);
  1887. });
  1888. });
  1889. }
  1890. var stats = function(self, options, callback) {
  1891. // Build command object
  1892. var commandObject = {
  1893. collStats:self.s.name
  1894. }
  1895. // Check if we have the scale value
  1896. if(options['scale'] != null) commandObject['scale'] = options['scale'];
  1897. options = shallowClone(options);
  1898. // Ensure we have the right read preference inheritance
  1899. options = getReadPreference(self, options, self.s.db, self);
  1900. // Execute the command
  1901. self.s.db.command(commandObject, options, callback);
  1902. }
  1903. define.classMethod('stats', {callback: true, promise:true});
  1904. /**
  1905. * @typedef {Object} Collection~findAndModifyWriteOpResult
  1906. * @property {object} value Document returned from findAndModify command.
  1907. * @property {object} lastErrorObject The raw lastErrorObject returned from the command.
  1908. * @property {Number} ok Is 1 if the command executed correctly.
  1909. */
  1910. /**
  1911. * The callback format for inserts
  1912. * @callback Collection~findAndModifyCallback
  1913. * @param {MongoError} error An error instance representing the error during the execution.
  1914. * @param {Collection~findAndModifyWriteOpResult} result The result object if the command was executed successfully.
  1915. */
  1916. /**
  1917. * Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation.
  1918. *
  1919. * @method
  1920. * @param {object} filter Document selection filter.
  1921. * @param {object} [options=null] Optional settings.
  1922. * @param {object} [options.projection=null] Limits the fields to return for all matching documents.
  1923. * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents.
  1924. * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run.
  1925. * @param {Collection~findAndModifyCallback} [callback] The collection result callback
  1926. * @return {Promise} returns Promise if no callback passed
  1927. */
  1928. Collection.prototype.findOneAndDelete = function(filter, options, callback) {
  1929. var self = this;
  1930. if(typeof options == 'function') callback = options, options = {};
  1931. options = options || {};
  1932. // Basic validation
  1933. if(filter == null || typeof filter != 'object') throw toError('filter parameter must be an object');
  1934. // Execute using callback
  1935. if(typeof callback == 'function') return findOneAndDelete(self, filter, options, callback);
  1936. // Return a Promise
  1937. return new this.s.promiseLibrary(function(resolve, reject) {
  1938. options = options || {};
  1939. findOneAndDelete(self, filter, options, function(err, r) {
  1940. if(err) return reject(err);
  1941. resolve(r);
  1942. });
  1943. });
  1944. }
  1945. var findOneAndDelete = function(self, filter, options, callback) {
  1946. // Final options
  1947. var finalOptions = shallowClone(options);
  1948. finalOptions['fields'] = options.projection;
  1949. finalOptions['remove'] = true;
  1950. // Execute find and Modify
  1951. self.findAndModify(
  1952. filter
  1953. , options.sort
  1954. , null
  1955. , finalOptions
  1956. , callback
  1957. );
  1958. }
  1959. define.classMethod('findOneAndDelete', {callback: true, promise:true});
  1960. /**
  1961. * Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation.
  1962. *
  1963. * @method
  1964. * @param {object} filter Document selection filter.
  1965. * @param {object} replacement Document replacing the matching document.
  1966. * @param {object} [options=null] Optional settings.
  1967. * @param {object} [options.projection=null] Limits the fields to return for all matching documents.
  1968. * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents.
  1969. * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run.
  1970. * @param {boolean} [options.upsert=false] Upsert the document if it does not exist.
  1971. * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true.
  1972. * @param {Collection~findAndModifyCallback} [callback] The collection result callback
  1973. * @return {Promise} returns Promise if no callback passed
  1974. */
  1975. Collection.prototype.findOneAndReplace = function(filter, replacement, options, callback) {
  1976. var self = this;
  1977. if(typeof options == 'function') callback = options, options = {};
  1978. options = options || {};
  1979. // Basic validation
  1980. if(filter == null || typeof filter != 'object') throw toError('filter parameter must be an object');
  1981. if(replacement == null || typeof replacement != 'object') throw toError('replacement parameter must be an object');
  1982. // Execute using callback
  1983. if(typeof callback == 'function') return findOneAndReplace(self, filter, replacement, options, callback);
  1984. // Return a Promise
  1985. return new this.s.promiseLibrary(function(resolve, reject) {
  1986. options = options || {};
  1987. findOneAndReplace(self, filter, replacement, options, function(err, r) {
  1988. if(err) return reject(err);
  1989. resolve(r);
  1990. });
  1991. });
  1992. }
  1993. var findOneAndReplace = function(self, filter, replacement, options, callback) {
  1994. // Final options
  1995. var finalOptions = shallowClone(options);
  1996. finalOptions['fields'] = options.projection;
  1997. finalOptions['update'] = true;
  1998. finalOptions['new'] = typeof options.returnOriginal == 'boolean' ? !options.returnOriginal : false;
  1999. finalOptions['upsert'] = typeof options.upsert == 'boolean' ? options.upsert : false;
  2000. // Execute findAndModify
  2001. self.findAndModify(
  2002. filter
  2003. , options.sort
  2004. , replacement
  2005. , finalOptions
  2006. , callback
  2007. );
  2008. }
  2009. define.classMethod('findOneAndReplace', {callback: true, promise:true});
  2010. /**
  2011. * Find a document and update it in one atomic operation, requires a write lock for the duration of the operation.
  2012. *
  2013. * @method
  2014. * @param {object} filter Document selection filter.
  2015. * @param {object} update Update operations to be performed on the document
  2016. * @param {object} [options=null] Optional settings.
  2017. * @param {object} [options.projection=null] Limits the fields to return for all matching documents.
  2018. * @param {object} [options.sort=null] Determines which document the operation modifies if the query selects multiple documents.
  2019. * @param {number} [options.maxTimeMS=null] The maximum amount of time to allow the query to run.
  2020. * @param {boolean} [options.upsert=false] Upsert the document if it does not exist.
  2021. * @param {boolean} [options.returnOriginal=true] When false, returns the updated document rather than the original. The default is true.
  2022. * @param {Collection~findAndModifyCallback} [callback] The collection result callback
  2023. * @return {Promise} returns Promise if no callback passed
  2024. */
  2025. Collection.prototype.findOneAndUpdate = function(filter, update, options, callback) {
  2026. var self = this;
  2027. if(typeof options == 'function') callback = options, options = {};
  2028. options = options || {};
  2029. // Basic validation
  2030. if(filter == null || typeof filter != 'object') throw toError('filter parameter must be an object');
  2031. if(update == null || typeof update != 'object') throw toError('update parameter must be an object');
  2032. // Execute using callback
  2033. if(typeof callback == 'function') return findOneAndUpdate(self, filter, update, options, callback);
  2034. // Return a Promise
  2035. return new this.s.promiseLibrary(function(resolve, reject) {
  2036. options = options || {};
  2037. findOneAndUpdate(self, filter, update, options, function(err, r) {
  2038. if(err) return reject(err);
  2039. resolve(r);
  2040. });
  2041. });
  2042. }
  2043. var findOneAndUpdate = function(self, filter, update, options, callback) {
  2044. // Final options
  2045. var finalOptions = shallowClone(options);
  2046. finalOptions['fields'] = options.projection;
  2047. finalOptions['update'] = true;
  2048. finalOptions['new'] = options.returnOriginal !== void 0 ? !options.returnOriginal : false;
  2049. finalOptions['upsert'] = options.upsert !== void 0 ? !!options.upsert : false;
  2050. // Execute findAndModify
  2051. self.findAndModify(
  2052. filter
  2053. , options.sort
  2054. , update
  2055. , finalOptions
  2056. , callback
  2057. );
  2058. }
  2059. define.classMethod('findOneAndUpdate', {callback: true, promise:true});
  2060. /**
  2061. * Find and update a document.
  2062. * @method
  2063. * @param {object} query Query object to locate the object to modify.
  2064. * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate.
  2065. * @param {object} doc The fields/vals to be updated.
  2066. * @param {object} [options=null] Optional settings.
  2067. * @param {(number|string)} [options.w=null] The write concern.
  2068. * @param {number} [options.wtimeout=null] The write concern timeout.
  2069. * @param {boolean} [options.j=false] Specify a journal write concern.
  2070. * @param {boolean} [options.remove=false] Set to true to remove the object before returning.
  2071. * @param {boolean} [options.upsert=false] Perform an upsert operation.
  2072. * @param {boolean} [options.new=false] Set to true if you want to return the modified object rather than the original. Ignored for remove.
  2073. * @param {object} [options.fields=null] Object containing the field projection for the result returned from the operation.
  2074. * @param {Collection~findAndModifyCallback} [callback] The command result callback
  2075. * @return {Promise} returns Promise if no callback passed
  2076. * @deprecated use findOneAndUpdate, findOneAndReplace or findOneAndDelete instead
  2077. */
  2078. Collection.prototype.findAndModify = function(query, sort, doc, options, callback) {
  2079. var self = this;
  2080. var args = Array.prototype.slice.call(arguments, 1);
  2081. callback = args.pop();
  2082. if(typeof callback != 'function') args.push(callback);
  2083. sort = args.length ? args.shift() || [] : [];
  2084. doc = args.length ? args.shift() : null;
  2085. options = args.length ? args.shift() || {} : {};
  2086. // Clone options
  2087. options = shallowClone(options);
  2088. // Force read preference primary
  2089. options.readPreference = ReadPreference.PRIMARY;
  2090. // Execute using callback
  2091. if(typeof callback == 'function') return findAndModify(self, query, sort, doc, options, callback);
  2092. // Return a Promise
  2093. return new this.s.promiseLibrary(function(resolve, reject) {
  2094. options = options || {};
  2095. findAndModify(self, query, sort, doc, options, function(err, r) {
  2096. if(err) return reject(err);
  2097. resolve(r);
  2098. });
  2099. });
  2100. }
  2101. var findAndModify = function(self, query, sort, doc, options, callback) {
  2102. // Create findAndModify command object
  2103. var queryObject = {
  2104. 'findandmodify': self.s.name
  2105. , 'query': query
  2106. };
  2107. sort = formattedOrderClause(sort);
  2108. if(sort) {
  2109. queryObject.sort = sort;
  2110. }
  2111. queryObject.new = options.new ? true : false;
  2112. queryObject.remove = options.remove ? true : false;
  2113. queryObject.upsert = options.upsert ? true : false;
  2114. if(options.fields) {
  2115. queryObject.fields = options.fields;
  2116. }
  2117. if(doc && !options.remove) {
  2118. queryObject.update = doc;
  2119. }
  2120. if(options.maxTimeMS)
  2121. queryObject.maxTimeMS = options.maxTimeMS;
  2122. // Either use override on the function, or go back to default on either the collection
  2123. // level or db
  2124. if(options['serializeFunctions'] != null) {
  2125. options['serializeFunctions'] = options['serializeFunctions'];
  2126. } else {
  2127. options['serializeFunctions'] = self.s.serializeFunctions;
  2128. }
  2129. // No check on the documents
  2130. options.checkKeys = false;
  2131. // Get the write concern settings
  2132. var finalOptions = writeConcern(options, self.s.db, self, options);
  2133. // Decorate the findAndModify command with the write Concern
  2134. if(finalOptions.writeConcern) {
  2135. queryObject.writeConcern = finalOptions.writeConcern;
  2136. }
  2137. // Have we specified bypassDocumentValidation
  2138. if(typeof finalOptions.bypassDocumentValidation == 'boolean') {
  2139. queryObject.bypassDocumentValidation = finalOptions.bypassDocumentValidation;
  2140. }
  2141. // Have we specified collation
  2142. decorateWithCollation(queryObject, self, options);
  2143. // Execute the command
  2144. self.s.db.command(queryObject
  2145. , options, function(err, result) {
  2146. if(err) return handleCallback(callback, err, null);
  2147. return handleCallback(callback, null, result);
  2148. });
  2149. }
  2150. define.classMethod('findAndModify', {callback: true, promise:true});
  2151. /**
  2152. * Find and remove a document.
  2153. * @method
  2154. * @param {object} query Query object to locate the object to modify.
  2155. * @param {array} sort If multiple docs match, choose the first one in the specified sort order as the object to manipulate.
  2156. * @param {object} [options=null] Optional settings.
  2157. * @param {(number|string)} [options.w=null] The write concern.
  2158. * @param {number} [options.wtimeout=null] The write concern timeout.
  2159. * @param {boolean} [options.j=false] Specify a journal write concern.
  2160. * @param {Collection~resultCallback} [callback] The command result callback
  2161. * @return {Promise} returns Promise if no callback passed
  2162. * @deprecated use findOneAndDelete instead
  2163. */
  2164. Collection.prototype.findAndRemove = function(query, sort, options, callback) {
  2165. var self = this;
  2166. var args = Array.prototype.slice.call(arguments, 1);
  2167. callback = args.pop();
  2168. if(typeof callback != 'function') args.push(callback);
  2169. sort = args.length ? args.shift() || [] : [];
  2170. options = args.length ? args.shift() || {} : {};
  2171. // Execute using callback
  2172. if(typeof callback == 'function') return findAndRemove(self, query, sort, options, callback);
  2173. // Return a Promise
  2174. return new this.s.promiseLibrary(function(resolve, reject) {
  2175. findAndRemove(self, query, sort, options, function(err, r) {
  2176. if(err) return reject(err);
  2177. resolve(r);
  2178. });
  2179. });
  2180. }
  2181. var findAndRemove = function(self, query, sort, options, callback) {
  2182. // Add the remove option
  2183. options['remove'] = true;
  2184. // Execute the callback
  2185. self.findAndModify(query, sort, null, options, callback);
  2186. }
  2187. define.classMethod('findAndRemove', {callback: true, promise:true});
  2188. function decorateWithWriteConcern(command, self, options) {
  2189. // Do we support collation 3.4 and higher
  2190. var capabilities = self.s.topology.capabilities();
  2191. // Do we support write concerns 3.4 and higher
  2192. if(capabilities && capabilities.commandsTakeWriteConcern) {
  2193. // Get the write concern settings
  2194. var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options);
  2195. // Add the write concern to the command
  2196. if(finalOptions.writeConcern) {
  2197. command.writeConcern = finalOptions.writeConcern;
  2198. }
  2199. }
  2200. }
  2201. function decorateWithCollation(command, self, options) {
  2202. // Do we support collation 3.4 and higher
  2203. var capabilities = self.s.topology.capabilities();
  2204. // Do we support write concerns 3.4 and higher
  2205. if(capabilities && capabilities.commandsTakeCollation) {
  2206. if(options.collation && typeof options.collation == 'object') {
  2207. command.collation = options.collation;
  2208. }
  2209. }
  2210. }
  2211. /**
  2212. * Execute an aggregation framework pipeline against the collection, needs MongoDB >= 2.2
  2213. * @method
  2214. * @param {object} pipeline Array containing all the aggregation framework commands for the execution.
  2215. * @param {object} [options=null] Optional settings.
  2216. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  2217. * @param {object} [options.cursor=null] Return the query as cursor, on 2.6 > it returns as a real cursor on pre 2.6 it returns as an emulated cursor.
  2218. * @param {number} [options.cursor.batchSize=null] The batchSize for the cursor
  2219. * @param {boolean} [options.explain=false] Explain returns the aggregation execution plan (requires mongodb 2.6 >).
  2220. * @param {boolean} [options.allowDiskUse=false] allowDiskUse lets the server know if it can use disk to store temporary results for the aggregation (requires mongodb 2.6 >).
  2221. * @param {number} [options.maxTimeMS=null] maxTimeMS specifies a cumulative time limit in milliseconds for processing operations on the cursor. MongoDB interrupts the operation at the earliest following interrupt point.
  2222. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  2223. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
  2224. * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.
  2225. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
  2226. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
  2227. * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  2228. * @param {Collection~resultCallback} callback The command result callback
  2229. * @return {(null|AggregationCursor)}
  2230. */
  2231. Collection.prototype.aggregate = function(pipeline, options, callback) {
  2232. var self = this;
  2233. if(Array.isArray(pipeline)) {
  2234. // Set up callback if one is provided
  2235. if(typeof options == 'function') {
  2236. callback = options;
  2237. options = {};
  2238. }
  2239. // If we have no options or callback we are doing
  2240. // a cursor based aggregation
  2241. if(options == null && callback == null) {
  2242. options = {};
  2243. }
  2244. } else {
  2245. // Aggregation pipeline passed as arguments on the method
  2246. var args = Array.prototype.slice.call(arguments, 0);
  2247. // Get the callback
  2248. callback = args.pop();
  2249. // Get the possible options object
  2250. var opts = args[args.length - 1];
  2251. // If it contains any of the admissible options pop it of the args
  2252. options = opts && (opts.readPreference
  2253. || opts.explain || opts.cursor || opts.out
  2254. || opts.maxTimeMS || opts.allowDiskUse) ? args.pop() : {};
  2255. // Left over arguments is the pipeline
  2256. pipeline = args;
  2257. }
  2258. // Ignore readConcern option
  2259. var ignoreReadConcern = false;
  2260. // Build the command
  2261. var command = { aggregate : this.s.name, pipeline : pipeline};
  2262. // If out was specified
  2263. if(typeof options.out == 'string') {
  2264. pipeline.push({$out: options.out});
  2265. // Ignore read concern
  2266. ignoreReadConcern = true;
  2267. } else if(pipeline.length > 0 && pipeline[pipeline.length - 1]['$out']) {
  2268. ignoreReadConcern = true;
  2269. }
  2270. // Decorate command with writeConcern if out has been specified
  2271. if(pipeline.length > 0 && pipeline[pipeline.length - 1]['$out']) {
  2272. decorateWithWriteConcern(command, self, options);
  2273. }
  2274. // Have we specified collation
  2275. decorateWithCollation(command, self, options);
  2276. // If we have bypassDocumentValidation set
  2277. if(typeof options.bypassDocumentValidation == 'boolean') {
  2278. command.bypassDocumentValidation = options.bypassDocumentValidation;
  2279. }
  2280. // Do we have a readConcern specified
  2281. if(!ignoreReadConcern && this.s.readConcern) {
  2282. command.readConcern = this.s.readConcern;
  2283. }
  2284. // If we have allowDiskUse defined
  2285. if(options.allowDiskUse) command.allowDiskUse = options.allowDiskUse;
  2286. if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS;
  2287. options = shallowClone(options);
  2288. // Ensure we have the right read preference inheritance
  2289. options = getReadPreference(this, options, this.s.db, this);
  2290. // If explain has been specified add it
  2291. if (options.explain) command.explain = options.explain;
  2292. // Validate that cursor options is valid
  2293. if(options.cursor != null && typeof options.cursor != 'object') {
  2294. throw toError('cursor options must be an object');
  2295. }
  2296. if (this.s.topology.capabilities().hasAggregationCursor) {
  2297. options.cursor = options.cursor || { batchSize : 1000 };
  2298. command.cursor = options.cursor;
  2299. }
  2300. // promiseLibrary
  2301. options.promiseLibrary = this.s.promiseLibrary;
  2302. // Set the AggregationCursor constructor
  2303. options.cursorFactory = AggregationCursor;
  2304. if(typeof callback != 'function') {
  2305. if(!this.s.topology.capabilities()) {
  2306. throw new MongoError('cannot connect to server');
  2307. }
  2308. // Allow disk usage command
  2309. if(typeof options.allowDiskUse == 'boolean') command.allowDiskUse = options.allowDiskUse;
  2310. if(typeof options.maxTimeMS == 'number') command.maxTimeMS = options.maxTimeMS;
  2311. // Execute the cursor
  2312. return this.s.topology.cursor(this.s.namespace, command, options);
  2313. }
  2314. if (options.cursor) {
  2315. var cursor = this.s.topology.cursor(this.s.namespace, command, options);
  2316. return cursor.toArray(function(err, result) {
  2317. if (err) {
  2318. return handleCallback(callback, err);
  2319. }
  2320. handleCallback(callback, null, result);
  2321. });
  2322. }
  2323. // For legacy server versions, we execute the command and format the result
  2324. this.s.db.command(command, options, function(err, result) {
  2325. if(err) {
  2326. handleCallback(callback, err);
  2327. } else if(result['err'] || result['errmsg']) {
  2328. handleCallback(callback, toError(result));
  2329. } else if(typeof result == 'object' && result['serverPipeline']) {
  2330. handleCallback(callback, null, result['serverPipeline']);
  2331. } else if(typeof result == 'object' && result['stages']) {
  2332. handleCallback(callback, null, result['stages']);
  2333. } else {
  2334. handleCallback(callback, null, result.result);
  2335. }
  2336. });
  2337. }
  2338. define.classMethod('aggregate', {callback: true, promise:false});
  2339. /**
  2340. * The callback format for results
  2341. * @callback Collection~parallelCollectionScanCallback
  2342. * @param {MongoError} error An error instance representing the error during the execution.
  2343. * @param {Cursor[]} cursors A list of cursors returned allowing for parallel reading of collection.
  2344. */
  2345. /**
  2346. * Return N number of parallel cursors for a collection allowing parallel reading of entire collection. There are
  2347. * no ordering guarantees for returned results.
  2348. * @method
  2349. * @param {object} [options=null] Optional settings.
  2350. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  2351. * @param {number} [options.batchSize=null] Set the batchSize for the getMoreCommand when iterating over the query results.
  2352. * @param {number} [options.numCursors=1] The maximum number of parallel command cursors to return (the number of returned cursors will be in the range 1:numCursors)
  2353. * @param {boolean} [options.raw=false] Return all BSON documents as Raw Buffer documents.
  2354. * @param {Collection~parallelCollectionScanCallback} [callback] The command result callback
  2355. * @return {Promise} returns Promise if no callback passed
  2356. */
  2357. Collection.prototype.parallelCollectionScan = function(options, callback) {
  2358. var self = this;
  2359. if(typeof options == 'function') callback = options, options = {numCursors: 1};
  2360. // Set number of cursors to 1
  2361. options.numCursors = options.numCursors || 1;
  2362. options.batchSize = options.batchSize || 1000;
  2363. options = shallowClone(options);
  2364. // Ensure we have the right read preference inheritance
  2365. options = getReadPreference(this, options, this.s.db, this);
  2366. // Add a promiseLibrary
  2367. options.promiseLibrary = this.s.promiseLibrary;
  2368. // Execute using callback
  2369. if(typeof callback == 'function') return parallelCollectionScan(self, options, callback);
  2370. // Return a Promise
  2371. return new this.s.promiseLibrary(function(resolve, reject) {
  2372. parallelCollectionScan(self, options, function(err, r) {
  2373. if(err) return reject(err);
  2374. resolve(r);
  2375. });
  2376. });
  2377. }
  2378. var parallelCollectionScan = function(self, options, callback) {
  2379. // Create command object
  2380. var commandObject = {
  2381. parallelCollectionScan: self.s.name
  2382. , numCursors: options.numCursors
  2383. }
  2384. // Do we have a readConcern specified
  2385. if(self.s.readConcern) {
  2386. commandObject.readConcern = self.s.readConcern;
  2387. }
  2388. // Store the raw value
  2389. var raw = options.raw;
  2390. delete options['raw'];
  2391. // Execute the command
  2392. self.s.db.command(commandObject, options, function(err, result) {
  2393. if(err) return handleCallback(callback, err, null);
  2394. if(result == null) return handleCallback(callback, new Error("no result returned for parallelCollectionScan"), null);
  2395. var cursors = [];
  2396. // Add the raw back to the option
  2397. if(raw) options.raw = raw;
  2398. // Create command cursors for each item
  2399. for(var i = 0; i < result.cursors.length; i++) {
  2400. var rawId = result.cursors[i].cursor.id
  2401. // Convert cursorId to Long if needed
  2402. var cursorId = typeof rawId == 'number' ? Long.fromNumber(rawId) : rawId;
  2403. // Add a command cursor
  2404. cursors.push(self.s.topology.cursor(self.s.namespace, cursorId, options));
  2405. }
  2406. handleCallback(callback, null, cursors);
  2407. });
  2408. }
  2409. define.classMethod('parallelCollectionScan', {callback: true, promise:true});
  2410. /**
  2411. * Execute the geoNear command to search for items in the collection
  2412. *
  2413. * @method
  2414. * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order.
  2415. * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order.
  2416. * @param {object} [options=null] Optional settings.
  2417. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  2418. * @param {number} [options.num=null] Max number of results to return.
  2419. * @param {number} [options.minDistance=null] Include results starting at minDistance from a point (2.6 or higher)
  2420. * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point.
  2421. * @param {number} [options.distanceMultiplier=null] Include a value to multiply the distances with allowing for range conversions.
  2422. * @param {object} [options.query=null] Filter the results by a query.
  2423. * @param {boolean} [options.spherical=false] Perform query using a spherical model.
  2424. * @param {boolean} [options.uniqueDocs=false] The closest location in a document to the center of the search region will always be returned MongoDB > 2.X.
  2425. * @param {boolean} [options.includeLocs=false] Include the location data fields in the top level of the results MongoDB > 2.X.
  2426. * @param {Collection~resultCallback} [callback] The command result callback
  2427. * @return {Promise} returns Promise if no callback passed
  2428. */
  2429. Collection.prototype.geoNear = function(x, y, options, callback) {
  2430. var self = this;
  2431. var point = typeof(x) == 'object' && x
  2432. , args = Array.prototype.slice.call(arguments, point?1:2);
  2433. callback = args.pop();
  2434. if(typeof callback != 'function') args.push(callback);
  2435. // Fetch all commands
  2436. options = args.length ? args.shift() || {} : {};
  2437. // Execute using callback
  2438. if(typeof callback == 'function') return geoNear(self, x, y, point, options, callback);
  2439. // Return a Promise
  2440. return new this.s.promiseLibrary(function(resolve, reject) {
  2441. geoNear(self, x, y, point, options, function(err, r) {
  2442. if(err) return reject(err);
  2443. resolve(r);
  2444. });
  2445. });
  2446. }
  2447. var geoNear = function(self, x, y, point, options, callback) {
  2448. // Build command object
  2449. var commandObject = {
  2450. geoNear:self.s.name,
  2451. near: point || [x, y]
  2452. }
  2453. options = shallowClone(options);
  2454. // Ensure we have the right read preference inheritance
  2455. options = getReadPreference(self, options, self.s.db, self);
  2456. // Exclude readPreference and existing options to prevent user from
  2457. // shooting themselves in the foot
  2458. var exclude = {
  2459. readPreference: true,
  2460. geoNear: true,
  2461. near: true
  2462. };
  2463. // Filter out any excluded objects
  2464. commandObject = decorateCommand(commandObject, options, exclude);
  2465. // Do we have a readConcern specified
  2466. if(self.s.readConcern) {
  2467. commandObject.readConcern = self.s.readConcern;
  2468. }
  2469. // Have we specified collation
  2470. decorateWithCollation(commandObject, self, options);
  2471. // Execute the command
  2472. self.s.db.command(commandObject, options, function (err, res) {
  2473. if(err) return handleCallback(callback, err);
  2474. if(res.err || res.errmsg) return handleCallback(callback, toError(res));
  2475. // should we only be returning res.results here? Not sure if the user
  2476. // should see the other return information
  2477. handleCallback(callback, null, res);
  2478. });
  2479. }
  2480. define.classMethod('geoNear', {callback: true, promise:true});
  2481. /**
  2482. * Execute a geo search using a geo haystack index on a collection.
  2483. *
  2484. * @method
  2485. * @param {number} x Point to search on the x axis, ensure the indexes are ordered in the same order.
  2486. * @param {number} y Point to search on the y axis, ensure the indexes are ordered in the same order.
  2487. * @param {object} [options=null] Optional settings.
  2488. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  2489. * @param {number} [options.maxDistance=null] Include results up to maxDistance from the point.
  2490. * @param {object} [options.search=null] Filter the results by a query.
  2491. * @param {number} [options.limit=false] Max number of results to return.
  2492. * @param {Collection~resultCallback} [callback] The command result callback
  2493. * @return {Promise} returns Promise if no callback passed
  2494. */
  2495. Collection.prototype.geoHaystackSearch = function(x, y, options, callback) {
  2496. var self = this;
  2497. var args = Array.prototype.slice.call(arguments, 2);
  2498. callback = args.pop();
  2499. if(typeof callback != 'function') args.push(callback);
  2500. // Fetch all commands
  2501. options = args.length ? args.shift() || {} : {};
  2502. // Execute using callback
  2503. if(typeof callback == 'function') return geoHaystackSearch(self, x, y, options, callback);
  2504. // Return a Promise
  2505. return new this.s.promiseLibrary(function(resolve, reject) {
  2506. geoHaystackSearch(self, x, y, options, function(err, r) {
  2507. if(err) return reject(err);
  2508. resolve(r);
  2509. });
  2510. });
  2511. }
  2512. var geoHaystackSearch = function(self, x, y, options, callback) {
  2513. // Build command object
  2514. var commandObject = {
  2515. geoSearch: self.s.name,
  2516. near: [x, y]
  2517. }
  2518. // Remove read preference from hash if it exists
  2519. commandObject = decorateCommand(commandObject, options, {readPreference: true});
  2520. options = shallowClone(options);
  2521. // Ensure we have the right read preference inheritance
  2522. options = getReadPreference(self, options, self.s.db, self);
  2523. // Do we have a readConcern specified
  2524. if(self.s.readConcern) {
  2525. commandObject.readConcern = self.s.readConcern;
  2526. }
  2527. // Execute the command
  2528. self.s.db.command(commandObject, options, function (err, res) {
  2529. if(err) return handleCallback(callback, err);
  2530. if(res.err || res.errmsg) handleCallback(callback, toError(res));
  2531. // should we only be returning res.results here? Not sure if the user
  2532. // should see the other return information
  2533. handleCallback(callback, null, res);
  2534. });
  2535. }
  2536. define.classMethod('geoHaystackSearch', {callback: true, promise:true});
  2537. /**
  2538. * Group function helper
  2539. * @ignore
  2540. */
  2541. // var groupFunction = function () {
  2542. // var c = db[ns].find(condition);
  2543. // var map = new Map();
  2544. // var reduce_function = reduce;
  2545. //
  2546. // while (c.hasNext()) {
  2547. // var obj = c.next();
  2548. // var key = {};
  2549. //
  2550. // for (var i = 0, len = keys.length; i < len; ++i) {
  2551. // var k = keys[i];
  2552. // key[k] = obj[k];
  2553. // }
  2554. //
  2555. // var aggObj = map.get(key);
  2556. //
  2557. // if (aggObj == null) {
  2558. // var newObj = Object.extend({}, key);
  2559. // aggObj = Object.extend(newObj, initial);
  2560. // map.put(key, aggObj);
  2561. // }
  2562. //
  2563. // reduce_function(obj, aggObj);
  2564. // }
  2565. //
  2566. // return { "result": map.values() };
  2567. // }.toString();
  2568. var groupFunction = 'function () {\nvar c = db[ns].find(condition);\nvar map = new Map();\nvar reduce_function = reduce;\n\nwhile (c.hasNext()) {\nvar obj = c.next();\nvar key = {};\n\nfor (var i = 0, len = keys.length; i < len; ++i) {\nvar k = keys[i];\nkey[k] = obj[k];\n}\n\nvar aggObj = map.get(key);\n\nif (aggObj == null) {\nvar newObj = Object.extend({}, key);\naggObj = Object.extend(newObj, initial);\nmap.put(key, aggObj);\n}\n\nreduce_function(obj, aggObj);\n}\n\nreturn { "result": map.values() };\n}';
  2569. /**
  2570. * Run a group command across a collection
  2571. *
  2572. * @method
  2573. * @param {(object|array|function|code)} keys An object, array or function expressing the keys to group by.
  2574. * @param {object} condition An optional condition that must be true for a row to be considered.
  2575. * @param {object} initial Initial value of the aggregation counter object.
  2576. * @param {(function|Code)} reduce The reduce function aggregates (reduces) the objects iterated
  2577. * @param {(function|Code)} finalize An optional function to be run on each item in the result set just before the item is returned.
  2578. * @param {boolean} command Specify if you wish to run using the internal group command or using eval, default is true.
  2579. * @param {object} [options=null] Optional settings.
  2580. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  2581. * @param {Collection~resultCallback} [callback] The command result callback
  2582. * @return {Promise} returns Promise if no callback passed
  2583. * @deprecated MongoDB 3.6 or higher will no longer support the group command. We recommend rewriting using the aggregation framework.
  2584. */
  2585. Collection.prototype.group = function(keys, condition, initial, reduce, finalize, command, options, callback) {
  2586. var self = this;
  2587. var args = Array.prototype.slice.call(arguments, 3);
  2588. callback = args.pop();
  2589. if(typeof callback != 'function') args.push(callback);
  2590. // Fetch all commands
  2591. reduce = args.length ? args.shift() : null;
  2592. finalize = args.length ? args.shift() : null;
  2593. command = args.length ? args.shift() : null;
  2594. options = args.length ? args.shift() || {} : {};
  2595. // Make sure we are backward compatible
  2596. if(!(typeof finalize == 'function')) {
  2597. command = finalize;
  2598. finalize = null;
  2599. }
  2600. if (!Array.isArray(keys) && keys instanceof Object && typeof(keys) !== 'function' && !(keys._bsontype == 'Code')) {
  2601. keys = Object.keys(keys);
  2602. }
  2603. if(typeof reduce === 'function') {
  2604. reduce = reduce.toString();
  2605. }
  2606. if(typeof finalize === 'function') {
  2607. finalize = finalize.toString();
  2608. }
  2609. // Set up the command as default
  2610. command = command == null ? true : command;
  2611. // Execute using callback
  2612. if(typeof callback == 'function') return group(self, keys, condition, initial, reduce, finalize, command, options, callback);
  2613. // Return a Promise
  2614. return new this.s.promiseLibrary(function(resolve, reject) {
  2615. group(self, keys, condition, initial, reduce, finalize, command, options, function(err, r) {
  2616. if(err) return reject(err);
  2617. resolve(r);
  2618. });
  2619. });
  2620. }
  2621. var group = function(self, keys, condition, initial, reduce, finalize, command, options, callback) {
  2622. // Execute using the command
  2623. if(command) {
  2624. var reduceFunction = reduce && reduce._bsontype == 'Code'
  2625. ? reduce
  2626. : new Code(reduce);
  2627. var selector = {
  2628. group: {
  2629. 'ns': self.s.name
  2630. , '$reduce': reduceFunction
  2631. , 'cond': condition
  2632. , 'initial': initial
  2633. , 'out': "inline"
  2634. }
  2635. };
  2636. // if finalize is defined
  2637. if(finalize != null) selector.group['finalize'] = finalize;
  2638. // Set up group selector
  2639. if ('function' === typeof keys || (keys && keys._bsontype == 'Code')) {
  2640. selector.group.$keyf = keys && keys._bsontype == 'Code'
  2641. ? keys
  2642. : new Code(keys);
  2643. } else {
  2644. var hash = {};
  2645. keys.forEach(function (key) {
  2646. hash[key] = 1;
  2647. });
  2648. selector.group.key = hash;
  2649. }
  2650. options = shallowClone(options);
  2651. // Ensure we have the right read preference inheritance
  2652. options = getReadPreference(self, options, self.s.db, self);
  2653. // Do we have a readConcern specified
  2654. if(self.s.readConcern) {
  2655. selector.readConcern = self.s.readConcern;
  2656. }
  2657. // Have we specified collation
  2658. decorateWithCollation(selector, self, options);
  2659. // Execute command
  2660. self.s.db.command(selector, options, function(err, result) {
  2661. if(err) return handleCallback(callback, err, null);
  2662. handleCallback(callback, null, result.retval);
  2663. });
  2664. } else {
  2665. // Create execution scope
  2666. var scope = reduce != null && reduce._bsontype == 'Code'
  2667. ? reduce.scope
  2668. : {};
  2669. scope.ns = self.s.name;
  2670. scope.keys = keys;
  2671. scope.condition = condition;
  2672. scope.initial = initial;
  2673. // Pass in the function text to execute within mongodb.
  2674. var groupfn = groupFunction.replace(/ reduce;/, reduce.toString() + ';');
  2675. self.s.db.eval(new Code(groupfn, scope), function (err, results) {
  2676. if (err) return handleCallback(callback, err, null);
  2677. handleCallback(callback, null, results.result || results);
  2678. });
  2679. }
  2680. }
  2681. define.classMethod('group', {callback: true, promise:true});
  2682. /**
  2683. * Functions that are passed as scope args must
  2684. * be converted to Code instances.
  2685. * @ignore
  2686. */
  2687. function processScope (scope) {
  2688. if(!isObject(scope) || scope._bsontype == 'ObjectID') {
  2689. return scope;
  2690. }
  2691. var keys = Object.keys(scope);
  2692. var i = keys.length;
  2693. var key;
  2694. var new_scope = {};
  2695. while (i--) {
  2696. key = keys[i];
  2697. if ('function' == typeof scope[key]) {
  2698. new_scope[key] = new Code(String(scope[key]));
  2699. } else {
  2700. new_scope[key] = processScope(scope[key]);
  2701. }
  2702. }
  2703. return new_scope;
  2704. }
  2705. /**
  2706. * Run Map Reduce across a collection. Be aware that the inline option for out will return an array of results not a collection.
  2707. *
  2708. * @method
  2709. * @param {(function|string)} map The mapping function.
  2710. * @param {(function|string)} reduce The reduce function.
  2711. * @param {object} [options=null] Optional settings.
  2712. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  2713. * @param {object} [options.out=null] Sets the output target for the map reduce job. *{inline:1} | {replace:'collectionName'} | {merge:'collectionName'} | {reduce:'collectionName'}*
  2714. * @param {object} [options.query=null] Query filter object.
  2715. * @param {object} [options.sort=null] Sorts the input objects using this key. Useful for optimization, like sorting by the emit key for fewer reduces.
  2716. * @param {number} [options.limit=null] Number of objects to return from collection.
  2717. * @param {boolean} [options.keeptemp=false] Keep temporary data.
  2718. * @param {(function|string)} [options.finalize=null] Finalize function.
  2719. * @param {object} [options.scope=null] Can pass in variables that can be access from map/reduce/finalize.
  2720. * @param {boolean} [options.jsMode=false] It is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X.
  2721. * @param {boolean} [options.verbose=false] Provide statistics on job execution time.
  2722. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  2723. * @param {Collection~resultCallback} [callback] The command result callback
  2724. * @throws {MongoError}
  2725. * @return {Promise} returns Promise if no callback passed
  2726. */
  2727. Collection.prototype.mapReduce = function(map, reduce, options, callback) {
  2728. var self = this;
  2729. if('function' === typeof options) callback = options, options = {};
  2730. // Out must allways be defined (make sure we don't break weirdly on pre 1.8+ servers)
  2731. if(null == options.out) {
  2732. throw new Error("the out option parameter must be defined, see mongodb docs for possible values");
  2733. }
  2734. if('function' === typeof map) {
  2735. map = map.toString();
  2736. }
  2737. if('function' === typeof reduce) {
  2738. reduce = reduce.toString();
  2739. }
  2740. if('function' === typeof options.finalize) {
  2741. options.finalize = options.finalize.toString();
  2742. }
  2743. // Execute using callback
  2744. if(typeof callback == 'function') return mapReduce(self, map, reduce, options, callback);
  2745. // Return a Promise
  2746. return new this.s.promiseLibrary(function(resolve, reject) {
  2747. mapReduce(self, map, reduce, options, function(err, r, r1) {
  2748. if(err) return reject(err);
  2749. if(!r1) return resolve(r);
  2750. resolve({results: r, stats: r1});
  2751. });
  2752. });
  2753. }
  2754. var mapReduce = function(self, map, reduce, options, callback) {
  2755. var mapCommandHash = {
  2756. mapreduce: self.s.name
  2757. , map: map
  2758. , reduce: reduce
  2759. };
  2760. // Exclusion list
  2761. var exclusionList = ['readPreference'];
  2762. // Add any other options passed in
  2763. for(var n in options) {
  2764. if('scope' == n) {
  2765. mapCommandHash[n] = processScope(options[n]);
  2766. } else {
  2767. // Only include if not in exclusion list
  2768. if(exclusionList.indexOf(n) == -1) {
  2769. mapCommandHash[n] = options[n];
  2770. }
  2771. }
  2772. }
  2773. options = shallowClone(options);
  2774. // Ensure we have the right read preference inheritance
  2775. options = getReadPreference(self, options, self.s.db, self);
  2776. // If we have a read preference and inline is not set as output fail hard
  2777. if((options.readPreference != false && options.readPreference != 'primary')
  2778. && options['out'] && (options['out'].inline != 1 && options['out'] != 'inline')) {
  2779. // Force readPreference to primary
  2780. options.readPreference = 'primary';
  2781. // Decorate command with writeConcern if supported
  2782. decorateWithWriteConcern(mapCommandHash, self, options);
  2783. } else if(self.s.readConcern) {
  2784. mapCommandHash.readConcern = self.s.readConcern;
  2785. }
  2786. // Is bypassDocumentValidation specified
  2787. if(typeof options.bypassDocumentValidation == 'boolean') {
  2788. mapCommandHash.bypassDocumentValidation = options.bypassDocumentValidation;
  2789. }
  2790. // Have we specified collation
  2791. decorateWithCollation(mapCommandHash, self, options);
  2792. // Execute command
  2793. self.s.db.command(mapCommandHash, {readPreference:options.readPreference}, function (err, result) {
  2794. if(err) return handleCallback(callback, err);
  2795. // Check if we have an error
  2796. if(1 != result.ok || result.err || result.errmsg) {
  2797. return handleCallback(callback, toError(result));
  2798. }
  2799. // Create statistics value
  2800. var stats = {};
  2801. if(result.timeMillis) stats['processtime'] = result.timeMillis;
  2802. if(result.counts) stats['counts'] = result.counts;
  2803. if(result.timing) stats['timing'] = result.timing;
  2804. // invoked with inline?
  2805. if(result.results) {
  2806. // If we wish for no verbosity
  2807. if(options['verbose'] == null || !options['verbose']) {
  2808. return handleCallback(callback, null, result.results);
  2809. }
  2810. return handleCallback(callback, null, result.results, stats);
  2811. }
  2812. // The returned collection
  2813. var collection = null;
  2814. // If we have an object it's a different db
  2815. if(result.result != null && typeof result.result == 'object') {
  2816. var doc = result.result;
  2817. collection = self.s.db.db(doc.db).collection(doc.collection);
  2818. } else {
  2819. // Create a collection object that wraps the result collection
  2820. collection = self.s.db.collection(result.result)
  2821. }
  2822. // If we wish for no verbosity
  2823. if(options['verbose'] == null || !options['verbose']) {
  2824. return handleCallback(callback, err, collection);
  2825. }
  2826. // Return stats as third set of values
  2827. handleCallback(callback, err, collection, stats);
  2828. });
  2829. }
  2830. define.classMethod('mapReduce', {callback: true, promise:true});
  2831. /**
  2832. * Initiate a Out of order batch write operation. All operations will be buffered into insert/update/remove commands executed out of order.
  2833. *
  2834. * @method
  2835. * @param {object} [options=null] Optional settings.
  2836. * @param {(number|string)} [options.w=null] The write concern.
  2837. * @param {number} [options.wtimeout=null] The write concern timeout.
  2838. * @param {boolean} [options.j=false] Specify a journal write concern.
  2839. * @return {UnorderedBulkOperation}
  2840. */
  2841. Collection.prototype.initializeUnorderedBulkOp = function(options) {
  2842. options = options || {};
  2843. options.promiseLibrary = this.s.promiseLibrary;
  2844. return unordered(this.s.topology, this, options);
  2845. }
  2846. define.classMethod('initializeUnorderedBulkOp', {callback: false, promise:false, returns: [ordered.UnorderedBulkOperation]});
  2847. /**
  2848. * Initiate an In order bulk write operation, operations will be serially executed in the order they are added, creating a new operation for each switch in types.
  2849. *
  2850. * @method
  2851. * @param {object} [options=null] Optional settings.
  2852. * @param {(number|string)} [options.w=null] The write concern.
  2853. * @param {number} [options.wtimeout=null] The write concern timeout.
  2854. * @param {boolean} [options.j=false] Specify a journal write concern.
  2855. * @param {OrderedBulkOperation} callback The command result callback
  2856. * @return {null}
  2857. */
  2858. Collection.prototype.initializeOrderedBulkOp = function(options) {
  2859. options = options || {};
  2860. options.promiseLibrary = this.s.promiseLibrary;
  2861. return ordered(this.s.topology, this, options);
  2862. }
  2863. define.classMethod('initializeOrderedBulkOp', {callback: false, promise:false, returns: [ordered.OrderedBulkOperation]});
  2864. // Get write concern
  2865. var writeConcern = function(target, db, col, options) {
  2866. if(options.w != null || options.j != null || options.fsync != null) {
  2867. var opts = {};
  2868. if(options.w != null) opts.w = options.w;
  2869. if(options.wtimeout != null) opts.wtimeout = options.wtimeout;
  2870. if(options.j != null) opts.j = options.j;
  2871. if(options.fsync != null) opts.fsync = options.fsync;
  2872. target.writeConcern = opts;
  2873. } else if(col.writeConcern.w != null || col.writeConcern.j != null || col.writeConcern.fsync != null) {
  2874. target.writeConcern = col.writeConcern;
  2875. } else if(db.writeConcern.w != null || db.writeConcern.j != null || db.writeConcern.fsync != null) {
  2876. target.writeConcern = db.writeConcern;
  2877. }
  2878. return target
  2879. }
  2880. // Figure out the read preference
  2881. var getReadPreference = function(self, options, db) {
  2882. var r = null
  2883. if(options.readPreference) {
  2884. r = options.readPreference
  2885. } else if(self.s.readPreference) {
  2886. r = self.s.readPreference
  2887. } else if(db.s.readPreference) {
  2888. r = db.s.readPreference;
  2889. }
  2890. if(r instanceof ReadPreference) {
  2891. options.readPreference = new CoreReadPreference(r.mode, r.tags, {maxStalenessSeconds: r.maxStalenessSeconds});
  2892. } else if(typeof r == 'string') {
  2893. options.readPreference = new CoreReadPreference(r);
  2894. } else if(r && !(r instanceof ReadPreference) && typeof r == 'object') {
  2895. var mode = r.mode || r.preference;
  2896. if (mode && typeof mode == 'string') {
  2897. options.readPreference = new CoreReadPreference(mode, r.tags, {maxStalenessSeconds: r.maxStalenessSeconds});
  2898. }
  2899. }
  2900. return options;
  2901. }
  2902. var testForFields = {
  2903. limit: 1, sort: 1, fields:1, skip: 1, hint: 1, explain: 1, snapshot: 1, timeout: 1, tailable: 1, tailableRetryInterval: 1
  2904. , numberOfRetries: 1, awaitdata: 1, awaitData: 1, exhaust: 1, batchSize: 1, returnKey: 1, maxScan: 1, min: 1, max: 1, showDiskLoc: 1
  2905. , comment: 1, raw: 1, readPreference: 1, partial: 1, read: 1, dbName: 1, oplogReplay: 1, connection: 1, maxTimeMS: 1, transforms: 1
  2906. , collation: 1
  2907. , noCursorTimeout: 1
  2908. }
  2909. module.exports = Collection;