/node_modules/mongoose/node_modules/mongodb/lib/collection.js

https://bitbucket.org/coleman333/smartsite · JavaScript · 3143 lines · 1548 code · 426 blank · 1169 comment · 525 complexity · cd07cd466b16d64808c290bfbd7f811e MD5 · raw file

Large files are truncated click here to view the full file

  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('mongodb-core').ReadPreference,
  17. CommandCursor = require('./command_cursor'),
  18. Define = require('./metadata'),
  19. Cursor = require('./cursor'),
  20. unordered = require('./bulk/unordered'),
  21. ordered = require('./bulk/ordered'),
  22. ChangeStream = require('./change_stream'),
  23. executeOperation = require('./utils').executeOperation;
  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. * const MongoClient = require('mongodb').MongoClient;
  31. * const test = require('assert');
  32. * // Connection url
  33. * const url = 'mongodb://localhost:27017';
  34. * // Database Name
  35. * const dbName = 'test';
  36. * // Connect using MongoClient
  37. * MongoClient.connect(url, function(err, client) {
  38. * // Create a collection we want to drop later
  39. * const col = client.db(dbName).collection('createIndexExample1');
  40. * // Show that duplicate records got dropped
  41. * col.find({}).toArray(function(err, items) {
  42. * test.equal(null, err);
  43. * test.equal(4, items.length);
  44. * client.close();
  45. * });
  46. * });
  47. */
  48. var mergeKeys = ['readPreference', 'ignoreUndefined'];
  49. /**
  50. * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly)
  51. * @class
  52. * @property {string} collectionName Get the collection name.
  53. * @property {string} namespace Get the full collection namespace.
  54. * @property {object} writeConcern The current write concern values.
  55. * @property {object} readConcern The current read concern values.
  56. * @property {object} hint Get current index hint for collection.
  57. * @return {Collection} a Collection instance.
  58. */
  59. var Collection = function(db, topology, dbName, name, pkFactory, options) {
  60. checkCollectionName(name);
  61. // Unpack variables
  62. var internalHint = null;
  63. var slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk;
  64. var serializeFunctions =
  65. options == null || options.serializeFunctions == null
  66. ? db.s.options.serializeFunctions
  67. : options.serializeFunctions;
  68. var raw = options == null || options.raw == null ? db.s.options.raw : options.raw;
  69. var promoteLongs =
  70. options == null || options.promoteLongs == null
  71. ? db.s.options.promoteLongs
  72. : options.promoteLongs;
  73. var promoteValues =
  74. options == null || options.promoteValues == null
  75. ? db.s.options.promoteValues
  76. : options.promoteValues;
  77. var promoteBuffers =
  78. options == null || options.promoteBuffers == null
  79. ? db.s.options.promoteBuffers
  80. : options.promoteBuffers;
  81. var readPreference = null;
  82. var collectionHint = null;
  83. var namespace = f('%s.%s', dbName, name);
  84. // Get the promiseLibrary
  85. var promiseLibrary = options.promiseLibrary || Promise;
  86. // Assign the right collection level readPreference
  87. if (options && options.readPreference) {
  88. readPreference = options.readPreference;
  89. } else if (db.options.readPreference) {
  90. readPreference = db.options.readPreference;
  91. }
  92. // Set custom primary key factory if provided
  93. pkFactory = pkFactory == null ? ObjectID : pkFactory;
  94. // Internal state
  95. this.s = {
  96. // Set custom primary key factory if provided
  97. pkFactory: pkFactory,
  98. // Db
  99. db: db,
  100. // Topology
  101. topology: topology,
  102. // dbName
  103. dbName: dbName,
  104. // Options
  105. options: options,
  106. // Namespace
  107. namespace: namespace,
  108. // Read preference
  109. readPreference: readPreference,
  110. // SlaveOK
  111. slaveOk: slaveOk,
  112. // Serialize functions
  113. serializeFunctions: serializeFunctions,
  114. // Raw
  115. raw: raw,
  116. // promoteLongs
  117. promoteLongs: promoteLongs,
  118. // promoteValues
  119. promoteValues: promoteValues,
  120. // promoteBuffers
  121. promoteBuffers: promoteBuffers,
  122. // internalHint
  123. internalHint: internalHint,
  124. // collectionHint
  125. collectionHint: collectionHint,
  126. // Name
  127. name: name,
  128. // Promise library
  129. promiseLibrary: promiseLibrary,
  130. // Read Concern
  131. readConcern: options.readConcern
  132. };
  133. };
  134. var define = (Collection.define = new Define('Collection', Collection, false));
  135. Object.defineProperty(Collection.prototype, 'dbName', {
  136. enumerable: true,
  137. get: function() {
  138. return this.s.dbName;
  139. }
  140. });
  141. Object.defineProperty(Collection.prototype, 'collectionName', {
  142. enumerable: true,
  143. get: function() {
  144. return this.s.name;
  145. }
  146. });
  147. Object.defineProperty(Collection.prototype, 'namespace', {
  148. enumerable: true,
  149. get: function() {
  150. return this.s.namespace;
  151. }
  152. });
  153. Object.defineProperty(Collection.prototype, 'readConcern', {
  154. enumerable: true,
  155. get: function() {
  156. return this.s.readConcern || { level: 'local' };
  157. }
  158. });
  159. Object.defineProperty(Collection.prototype, 'writeConcern', {
  160. enumerable: true,
  161. get: function() {
  162. var ops = {};
  163. if (this.s.options.w != null) ops.w = this.s.options.w;
  164. if (this.s.options.j != null) ops.j = this.s.options.j;
  165. if (this.s.options.fsync != null) ops.fsync = this.s.options.fsync;
  166. if (this.s.options.wtimeout != null) ops.wtimeout = this.s.options.wtimeout;
  167. return ops;
  168. }
  169. });
  170. /**
  171. * @ignore
  172. */
  173. Object.defineProperty(Collection.prototype, 'hint', {
  174. enumerable: true,
  175. get: function() {
  176. return this.s.collectionHint;
  177. },
  178. set: function(v) {
  179. this.s.collectionHint = normalizeHintField(v);
  180. }
  181. });
  182. /**
  183. * Creates a cursor for a query that can be used to iterate over results from MongoDB
  184. * @method
  185. * @param {object} [query={}] The cursor query object.
  186. * @param {object} [options=null] Optional settings.
  187. * @param {number} [options.limit=0] Sets the limit of documents returned in the query.
  188. * @param {(array|object)} [options.sort=null] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc.
  189. * @param {object} [options.projection=null] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1}
  190. * @param {object} [options.fields=null] **Deprecated** Use `options.projection` instead
  191. * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination).
  192. * @param {Object} [options.hint=null] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1}
  193. * @param {boolean} [options.explain=false] Explain the query instead of returning the data.
  194. * @param {boolean} [options.snapshot=false] Snapshot query.
  195. * @param {boolean} [options.timeout=false] Specify if the cursor can timeout.
  196. * @param {boolean} [options.tailable=false] Specify if the cursor is tailable.
  197. * @param {number} [options.batchSize=0] Set the batchSize for the getMoreCommand when iterating over the query results.
  198. * @param {boolean} [options.returnKey=false] Only return the index key.
  199. * @param {number} [options.maxScan=null] Limit the number of items to scan.
  200. * @param {number} [options.min=null] Set index bounds.
  201. * @param {number} [options.max=null] Set index bounds.
  202. * @param {boolean} [options.showDiskLoc=false] Show disk location of results.
  203. * @param {string} [options.comment=null] You can put a $comment field on a query to make looking in the profiler logs simpler.
  204. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers.
  205. * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution.
  206. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types.
  207. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers.
  208. * @param {(ReadPreference|string)} [options.readPreference=null] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST).
  209. * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system
  210. * @param {number} [options.maxTimeMS=null] Number of miliseconds to wait before aborting the query.
  211. * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  212. * @param {ClientSession} [options.session] optional session to use for this operation
  213. * @throws {MongoError}
  214. * @return {Cursor}
  215. */
  216. Collection.prototype.find = function(query, options, callback) {
  217. let selector = query;
  218. // figuring out arguments
  219. if (typeof callback !== 'function') {
  220. if (typeof options === 'function') {
  221. callback = options;
  222. options = undefined;
  223. } else if (options == null) {
  224. callback = typeof selector === 'function' ? selector : undefined;
  225. selector = typeof selector === 'object' ? selector : undefined;
  226. }
  227. }
  228. // Ensure selector is not null
  229. selector = selector == null ? {} : selector;
  230. // Validate correctness off the selector
  231. var object = selector;
  232. if (Buffer.isBuffer(object)) {
  233. var object_size = object[0] | (object[1] << 8) | (object[2] << 16) | (object[3] << 24);
  234. if (object_size !== object.length) {
  235. var error = new Error(
  236. 'query selector raw message size does not match message header size [' +
  237. object.length +
  238. '] != [' +
  239. object_size +
  240. ']'
  241. );
  242. error.name = 'MongoError';
  243. throw error;
  244. }
  245. }
  246. // Check special case where we are using an objectId
  247. if (selector != null && selector._bsontype === 'ObjectID') {
  248. selector = { _id: selector };
  249. }
  250. if (!options) options = {};
  251. let projection = options.projection || options.fields;
  252. if (projection && !Buffer.isBuffer(projection) && Array.isArray(projection)) {
  253. projection = projection.length
  254. ? projection.reduce((result, field) => {
  255. result[field] = 1;
  256. return result;
  257. }, {})
  258. : { _id: 1 };
  259. }
  260. var newOptions = {};
  261. // Make a shallow copy of the collection options
  262. for (var key in this.s.options) {
  263. if (mergeKeys.indexOf(key) !== -1) {
  264. newOptions[key] = this.s.options[key];
  265. }
  266. }
  267. // Make a shallow copy of options
  268. for (var optKey in options) {
  269. newOptions[optKey] = options[optKey];
  270. }
  271. // Unpack options
  272. newOptions.skip = options.skip ? options.skip : 0;
  273. newOptions.limit = options.limit ? options.limit : 0;
  274. newOptions.raw = typeof options.raw === 'boolean' ? options.raw : this.s.raw;
  275. newOptions.hint = options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint;
  276. newOptions.timeout = typeof options.timeout === 'undefined' ? undefined : options.timeout;
  277. // // If we have overridden slaveOk otherwise use the default db setting
  278. newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk;
  279. // Add read preference if needed
  280. newOptions = getReadPreference(this, newOptions, this.s.db);
  281. // Set slave ok to true if read preference different from primary
  282. if (
  283. newOptions.readPreference != null &&
  284. (newOptions.readPreference !== 'primary' || newOptions.readPreference.mode !== 'primary')
  285. ) {
  286. newOptions.slaveOk = true;
  287. }
  288. // Ensure the query is an object
  289. if (selector != null && typeof selector !== 'object') {
  290. throw MongoError.create({ message: 'query selector must be an object', driver: true });
  291. }
  292. // Build the find command
  293. var findCommand = {
  294. find: this.s.namespace,
  295. limit: newOptions.limit,
  296. skip: newOptions.skip,
  297. query: selector
  298. };
  299. // Ensure we use the right await data option
  300. if (typeof newOptions.awaitdata === 'boolean') {
  301. newOptions.awaitData = newOptions.awaitdata;
  302. }
  303. // Translate to new command option noCursorTimeout
  304. if (typeof newOptions.timeout === 'boolean') newOptions.noCursorTimeout = newOptions.timeout;
  305. // Merge in options to command
  306. for (var name in newOptions) {
  307. if (newOptions[name] != null && name !== 'session') {
  308. findCommand[name] = newOptions[name];
  309. }
  310. }
  311. if (projection) findCommand.fields = projection;
  312. // Add db object to the new options
  313. newOptions.db = this.s.db;
  314. // Add the promise library
  315. newOptions.promiseLibrary = this.s.promiseLibrary;
  316. // Set raw if available at collection level
  317. if (newOptions.raw == null && typeof this.s.raw === 'boolean') newOptions.raw = this.s.raw;
  318. // Set promoteLongs if available at collection level
  319. if (newOptions.promoteLongs == null && typeof this.s.promoteLongs === 'boolean')
  320. newOptions.promoteLongs = this.s.promoteLongs;
  321. if (newOptions.promoteValues == null && typeof this.s.promoteValues === 'boolean')
  322. newOptions.promoteValues = this.s.promoteValues;
  323. if (newOptions.promoteBuffers == null && typeof this.s.promoteBuffers === 'boolean')
  324. newOptions.promoteBuffers = this.s.promoteBuffers;
  325. // Sort options
  326. if (findCommand.sort) {
  327. findCommand.sort = formattedOrderClause(findCommand.sort);
  328. }
  329. // Set the readConcern
  330. decorateWithReadConcern(findCommand, this, options);
  331. // Decorate find command with collation options
  332. decorateWithCollation(findCommand, this, options);
  333. // Create the cursor
  334. if (typeof callback === 'function')
  335. return handleCallback(
  336. callback,
  337. null,
  338. this.s.topology.cursor(this.s.namespace, findCommand, newOptions)
  339. );
  340. return this.s.topology.cursor(this.s.namespace, findCommand, newOptions);
  341. };
  342. define.classMethod('find', { callback: false, promise: false, returns: [Cursor] });
  343. /**
  344. * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field,
  345. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  346. * can be overridden by setting the **forceServerObjectId** flag.
  347. *
  348. * @method
  349. * @param {object} doc Document to insert.
  350. * @param {object} [options=null] Optional settings.
  351. * @param {(number|string)} [options.w=null] The write concern.
  352. * @param {number} [options.wtimeout=null] The write concern timeout.
  353. * @param {boolean} [options.j=false] Specify a journal write concern.
  354. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  355. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
  356. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  357. * @param {ClientSession} [options.session] optional session to use for this operation
  358. * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback
  359. * @return {Promise} returns Promise if no callback passed
  360. */
  361. Collection.prototype.insertOne = function(doc, options, callback) {
  362. if (typeof options === 'function') (callback = options), (options = {});
  363. options = options || {};
  364. // Add ignoreUndfined
  365. if (this.s.options.ignoreUndefined) {
  366. options = shallowClone(options);
  367. options.ignoreUndefined = this.s.options.ignoreUndefined;
  368. }
  369. return executeOperation(this.s.topology, insertOne, [this, doc, options, callback]);
  370. };
  371. var insertOne = function(self, doc, options, callback) {
  372. if (Array.isArray(doc)) {
  373. return callback(
  374. MongoError.create({ message: 'doc parameter must be an object', driver: true })
  375. );
  376. }
  377. insertDocuments(self, [doc], options, function(err, r) {
  378. if (callback == null) return;
  379. if (err && callback) return callback(err);
  380. // Workaround for pre 2.6 servers
  381. if (r == null) return callback(null, { result: { ok: 1 } });
  382. // Add values to top level to ensure crud spec compatibility
  383. r.insertedCount = r.result.n;
  384. r.insertedId = doc._id;
  385. if (callback) callback(null, r);
  386. });
  387. };
  388. var mapInserManyResults = function(docs, r) {
  389. var finalResult = {
  390. result: { ok: 1, n: r.insertedCount },
  391. ops: docs,
  392. insertedCount: r.insertedCount,
  393. insertedIds: r.insertedIds
  394. };
  395. if (r.getLastOp()) {
  396. finalResult.result.opTime = r.getLastOp();
  397. }
  398. return finalResult;
  399. };
  400. define.classMethod('insertOne', { callback: true, promise: true });
  401. /**
  402. * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field,
  403. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  404. * can be overridden by setting the **forceServerObjectId** flag.
  405. *
  406. * @method
  407. * @param {object[]} docs Documents to insert.
  408. * @param {object} [options=null] Optional settings.
  409. * @param {(number|string)} [options.w=null] The write concern.
  410. * @param {number} [options.wtimeout=null] The write concern timeout.
  411. * @param {boolean} [options.j=false] Specify a journal write concern.
  412. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  413. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
  414. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  415. * @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.
  416. * @param {ClientSession} [options.session] optional session to use for this operation
  417. * @param {Collection~insertWriteOpCallback} [callback] The command result callback
  418. * @return {Promise} returns Promise if no callback passed
  419. */
  420. Collection.prototype.insertMany = function(docs, options, callback) {
  421. var self = this;
  422. if (typeof options === 'function') (callback = options), (options = {});
  423. options = options ? shallowClone(options) : { ordered: true };
  424. if (!Array.isArray(docs) && typeof callback === 'function') {
  425. return callback(
  426. MongoError.create({ message: 'docs parameter must be an array of documents', driver: true })
  427. );
  428. } else if (!Array.isArray(docs)) {
  429. return new this.s.promiseLibrary(function(resolve, reject) {
  430. reject(
  431. MongoError.create({ message: 'docs parameter must be an array of documents', driver: true })
  432. );
  433. });
  434. }
  435. // If keep going set unordered
  436. options['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions;
  437. // Set up the force server object id
  438. var forceServerObjectId =
  439. typeof options.forceServerObjectId === 'boolean'
  440. ? options.forceServerObjectId
  441. : self.s.db.options.forceServerObjectId;
  442. // Do we want to force the server to assign the _id key
  443. if (forceServerObjectId !== true) {
  444. // Add _id if not specified
  445. for (var i = 0; i < docs.length; i++) {
  446. if (docs[i]._id == null) docs[i]._id = self.s.pkFactory.createPk();
  447. }
  448. }
  449. // Generate the bulk write operations
  450. var operations = [
  451. {
  452. insertMany: docs
  453. }
  454. ];
  455. return executeOperation(this.s.topology, bulkWrite, [this, operations, options, callback], {
  456. resultMutator: result => mapInserManyResults(docs, result)
  457. });
  458. };
  459. define.classMethod('insertMany', { callback: true, promise: true });
  460. /**
  461. * @typedef {Object} Collection~BulkWriteOpResult
  462. * @property {number} insertedCount Number of documents inserted.
  463. * @property {number} matchedCount Number of documents matched for update.
  464. * @property {number} modifiedCount Number of documents modified.
  465. * @property {number} deletedCount Number of documents deleted.
  466. * @property {number} upsertedCount Number of documents upserted.
  467. * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation
  468. * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation
  469. * @property {object} result The command result object.
  470. */
  471. /**
  472. * The callback format for inserts
  473. * @callback Collection~bulkWriteOpCallback
  474. * @param {BulkWriteError} error An error instance representing the error during the execution.
  475. * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully.
  476. */
  477. /**
  478. * Perform a bulkWrite operation without a fluent API
  479. *
  480. * Legal operation types are
  481. *
  482. * { insertOne: { document: { a: 1 } } }
  483. *
  484. * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
  485. *
  486. * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } }
  487. *
  488. * { deleteOne: { filter: {c:1} } }
  489. *
  490. * { deleteMany: { filter: {c:1} } }
  491. *
  492. * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}}
  493. *
  494. * If documents passed in do not contain the **_id** field,
  495. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  496. * can be overridden by setting the **forceServerObjectId** flag.
  497. *
  498. * @method
  499. * @param {object[]} operations Bulk operations to perform.
  500. * @param {object} [options=null] Optional settings.
  501. * @param {(number|string)} [options.w=null] The write concern.
  502. * @param {number} [options.wtimeout=null] The write concern timeout.
  503. * @param {boolean} [options.j=false] Specify a journal write concern.
  504. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  505. * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion.
  506. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  507. * @param {ClientSession} [options.session] optional session to use for this operation
  508. * @param {Collection~bulkWriteOpCallback} [callback] The command result callback
  509. * @return {Promise} returns Promise if no callback passed
  510. */
  511. Collection.prototype.bulkWrite = function(operations, options, callback) {
  512. if (typeof options === 'function') (callback = options), (options = {});
  513. options = options || { ordered: true };
  514. if (!Array.isArray(operations)) {
  515. throw MongoError.create({ message: 'operations must be an array of documents', driver: true });
  516. }
  517. return executeOperation(this.s.topology, bulkWrite, [this, operations, options, callback]);
  518. };
  519. var bulkWrite = function(self, operations, options, callback) {
  520. // Add ignoreUndfined
  521. if (self.s.options.ignoreUndefined) {
  522. options = shallowClone(options);
  523. options.ignoreUndefined = self.s.options.ignoreUndefined;
  524. }
  525. // Create the bulk operation
  526. var bulk =
  527. options.ordered === true || options.ordered == null
  528. ? self.initializeOrderedBulkOp(options)
  529. : self.initializeUnorderedBulkOp(options);
  530. // Do we have a collation
  531. var collation = false;
  532. // for each op go through and add to the bulk
  533. try {
  534. for (var i = 0; i < operations.length; i++) {
  535. // Get the operation type
  536. var key = Object.keys(operations[i])[0];
  537. // Check if we have a collation
  538. if (operations[i][key].collation) {
  539. collation = true;
  540. }
  541. // Pass to the raw bulk
  542. bulk.raw(operations[i]);
  543. }
  544. } catch (err) {
  545. return callback(err, null);
  546. }
  547. // Final options for write concern
  548. var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options);
  549. var writeCon = finalOptions.writeConcern ? finalOptions.writeConcern : {};
  550. var capabilities = self.s.topology.capabilities();
  551. // Did the user pass in a collation, check if our write server supports it
  552. if (collation && capabilities && !capabilities.commandsTakeCollation) {
  553. return callback(new MongoError(f('server/primary/mongos does not support collation')));
  554. }
  555. // Execute the bulk
  556. bulk.execute(writeCon, finalOptions, function(err, r) {
  557. // We have connection level error
  558. if (!r && err) {
  559. return callback(err, null);
  560. }
  561. r.insertedCount = r.nInserted;
  562. r.matchedCount = r.nMatched;
  563. r.modifiedCount = r.nModified || 0;
  564. r.deletedCount = r.nRemoved;
  565. r.upsertedCount = r.getUpsertedIds().length;
  566. r.upsertedIds = {};
  567. r.insertedIds = {};
  568. // Update the n
  569. r.n = r.insertedCount;
  570. // Inserted documents
  571. var inserted = r.getInsertedIds();
  572. // Map inserted ids
  573. for (var i = 0; i < inserted.length; i++) {
  574. r.insertedIds[inserted[i].index] = inserted[i]._id;
  575. }
  576. // Upserted documents
  577. var upserted = r.getUpsertedIds();
  578. // Map upserted ids
  579. for (i = 0; i < upserted.length; i++) {
  580. r.upsertedIds[upserted[i].index] = upserted[i]._id;
  581. }
  582. // Return the results
  583. callback(null, r);
  584. });
  585. };
  586. var insertDocuments = function(self, docs, options, callback) {
  587. if (typeof options === 'function') (callback = options), (options = {});
  588. options = options || {};
  589. // Ensure we are operating on an array op docs
  590. docs = Array.isArray(docs) ? docs : [docs];
  591. // Get the write concern options
  592. var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options);
  593. // If keep going set unordered
  594. if (finalOptions.keepGoing === true) finalOptions.ordered = false;
  595. finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions;
  596. // Set up the force server object id
  597. var forceServerObjectId =
  598. typeof options.forceServerObjectId === 'boolean'
  599. ? options.forceServerObjectId
  600. : self.s.db.options.forceServerObjectId;
  601. // Add _id if not specified
  602. if (forceServerObjectId !== true) {
  603. for (var i = 0; i < docs.length; i++) {
  604. if (docs[i]._id === void 0) docs[i]._id = self.s.pkFactory.createPk();
  605. }
  606. }
  607. // File inserts
  608. self.s.topology.insert(self.s.namespace, docs, finalOptions, function(err, result) {
  609. if (callback == null) return;
  610. if (err) return handleCallback(callback, err);
  611. if (result == null) return handleCallback(callback, null, null);
  612. if (result.result.code) return handleCallback(callback, toError(result.result));
  613. if (result.result.writeErrors)
  614. return handleCallback(callback, toError(result.result.writeErrors[0]));
  615. // Add docs to the list
  616. result.ops = docs;
  617. // Return the results
  618. handleCallback(callback, null, result);
  619. });
  620. };
  621. define.classMethod('bulkWrite', { callback: true, promise: true });
  622. /**
  623. * @typedef {Object} Collection~WriteOpResult
  624. * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany
  625. * @property {object} connection The connection object used for the operation.
  626. * @property {object} result The command result object.
  627. */
  628. /**
  629. * The callback format for inserts
  630. * @callback Collection~writeOpCallback
  631. * @param {MongoError} error An error instance representing the error during the execution.
  632. * @param {Collection~WriteOpResult} result The result object if the command was executed successfully.
  633. */
  634. /**
  635. * @typedef {Object} Collection~insertWriteOpResult
  636. * @property {Number} insertedCount The total amount of documents inserted.
  637. * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany
  638. * @property {Object.<Number, ObjectId>} insertedIds Map of the index of the inserted document to the id of the inserted document.
  639. * @property {object} connection The connection object used for the operation.
  640. * @property {object} result The raw command result object returned from MongoDB (content might vary by server version).
  641. * @property {Number} result.ok Is 1 if the command executed correctly.
  642. * @property {Number} result.n The total count of documents inserted.
  643. */
  644. /**
  645. * @typedef {Object} Collection~insertOneWriteOpResult
  646. * @property {Number} insertedCount The total amount of documents inserted.
  647. * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany
  648. * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation.
  649. * @property {object} connection The connection object used for the operation.
  650. * @property {object} result The raw command result object returned from MongoDB (content might vary by server version).
  651. * @property {Number} result.ok Is 1 if the command executed correctly.
  652. * @property {Number} result.n The total count of documents inserted.
  653. */
  654. /**
  655. * The callback format for inserts
  656. * @callback Collection~insertWriteOpCallback
  657. * @param {MongoError} error An error instance representing the error during the execution.
  658. * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully.
  659. */
  660. /**
  661. * The callback format for inserts
  662. * @callback Collection~insertOneWriteOpCallback
  663. * @param {MongoError} error An error instance representing the error during the execution.
  664. * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully.
  665. */
  666. /**
  667. * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field,
  668. * one will be added to each of the documents missing it by the driver, mutating the document. This behavior
  669. * can be overridden by setting the **forceServerObjectId** flag.
  670. *
  671. * @method
  672. * @param {(object|object[])} docs Documents to insert.
  673. * @param {object} [options=null] Optional settings.
  674. * @param {(number|string)} [options.w=null] The write concern.
  675. * @param {number} [options.wtimeout=null] The write concern timeout.
  676. * @param {boolean} [options.j=false] Specify a journal write concern.
  677. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object.
  678. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver.
  679. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  680. * @param {ClientSession} [options.session] optional session to use for this operation
  681. * @param {Collection~insertWriteOpCallback} [callback] The command result callback
  682. * @return {Promise} returns Promise if no callback passed
  683. * @deprecated Use insertOne, insertMany or bulkWrite
  684. */
  685. Collection.prototype.insert = function(docs, options, callback) {
  686. if (typeof options === 'function') (callback = options), (options = {});
  687. options = options || { ordered: false };
  688. docs = !Array.isArray(docs) ? [docs] : docs;
  689. if (options.keepGoing === true) {
  690. options.ordered = false;
  691. }
  692. return this.insertMany(docs, options, callback);
  693. };
  694. define.classMethod('insert', { callback: true, promise: true });
  695. /**
  696. * @typedef {Object} Collection~updateWriteOpResult
  697. * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version.
  698. * @property {Number} result.ok Is 1 if the command executed correctly.
  699. * @property {Number} result.n The total count of documents scanned.
  700. * @property {Number} result.nModified The total count of documents modified.
  701. * @property {Object} connection The connection object used for the operation.
  702. * @property {Number} matchedCount The number of documents that matched the filter.
  703. * @property {Number} modifiedCount The number of documents that were modified.
  704. * @property {Number} upsertedCount The number of documents upserted.
  705. * @property {Object} upsertedId The upserted id.
  706. * @property {ObjectId} upsertedId._id The upserted _id returned from the server.
  707. */
  708. /**
  709. * The callback format for inserts
  710. * @callback Collection~updateWriteOpCallback
  711. * @param {MongoError} error An error instance representing the error during the execution.
  712. * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully.
  713. */
  714. /**
  715. * Update a single document on MongoDB
  716. * @method
  717. * @param {object} filter The Filter used to select the document to update
  718. * @param {object} update The update operations to be applied to the document
  719. * @param {object} [options=null] Optional settings.
  720. * @param {boolean} [options.upsert=false] Update operation is an upsert.
  721. * @param {(number|string)} [options.w=null] The write concern.
  722. * @param {number} [options.wtimeout=null] The write concern timeout.
  723. * @param {boolean} [options.j=false] Specify a journal write concern.
  724. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  725. * @param {Array} [options.arrayFilters=null] optional list of array filters referenced in filtered positional operators
  726. * @param {ClientSession} [options.session] optional session to use for this operation
  727. * @param {Collection~updateWriteOpCallback} [callback] The command result callback
  728. * @return {Promise} returns Promise if no callback passed
  729. */
  730. Collection.prototype.updateOne = function(filter, update, options, callback) {
  731. if (typeof options === 'function') (callback = options), (options = {});
  732. options = options || {};
  733. var err = checkForAtomicOperators(update);
  734. if (err) {
  735. if (typeof callback === 'function') return callback(err);
  736. return this.s.promiseLibrary.reject(err);
  737. }
  738. options = shallowClone(options);
  739. // Add ignoreUndfined
  740. if (this.s.options.ignoreUndefined) {
  741. options = shallowClone(options);
  742. options.ignoreUndefined = this.s.options.ignoreUndefined;
  743. }
  744. return executeOperation(this.s.topology, updateOne, [this, filter, update, options, callback]);
  745. };
  746. var checkForAtomicOperators = function(update) {
  747. var keys = Object.keys(update);
  748. // same errors as the server would give for update doc lacking atomic operators
  749. if (keys.length === 0) {
  750. return toError('The update operation document must contain at least one atomic operator.');
  751. }
  752. if (keys[0][0] !== '$') {
  753. return toError('the update operation document must contain atomic operators.');
  754. }
  755. };
  756. var updateOne = function(self, filter, update, options, callback) {
  757. // Set single document update
  758. options.multi = false;
  759. // Execute update
  760. updateDocuments(self, filter, update, options, function(err, r) {
  761. if (callback == null) return;
  762. if (err && callback) return callback(err);
  763. if (r == null) return callback(null, { result: { ok: 1 } });
  764. r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n;
  765. r.upsertedId =
  766. Array.isArray(r.result.upserted) && r.result.upserted.length > 0
  767. ? r.result.upserted[0]
  768. : null;
  769. r.upsertedCount =
  770. Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0;
  771. r.matchedCount =
  772. Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n;
  773. if (callback) callback(null, r);
  774. });
  775. };
  776. define.classMethod('updateOne', { callback: true, promise: true });
  777. /**
  778. * Replace a document on MongoDB
  779. * @method
  780. * @param {object} filter The Filter used to select the document to update
  781. * @param {object} doc The Document that replaces the matching document
  782. * @param {object} [options=null] Optional settings.
  783. * @param {boolean} [options.upsert=false] Update operation is an upsert.
  784. * @param {(number|string)} [options.w=null] The write concern.
  785. * @param {number} [options.wtimeout=null] The write concern timeout.
  786. * @param {boolean} [options.j=false] Specify a journal write concern.
  787. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  788. * @param {ClientSession} [options.session] optional session to use for this operation
  789. * @param {Collection~updateWriteOpCallback} [callback] The command result callback
  790. * @return {Promise} returns Promise if no callback passed
  791. */
  792. Collection.prototype.replaceOne = function(filter, doc, options, callback) {
  793. if (typeof options === 'function') (callback = options), (options = {});
  794. options = shallowClone(options);
  795. // Add ignoreUndfined
  796. if (this.s.options.ignoreUndefined) {
  797. options = shallowClone(options);
  798. options.ignoreUndefined = this.s.options.ignoreUndefined;
  799. }
  800. return executeOperation(this.s.topology, replaceOne, [this, filter, doc, options, callback]);
  801. };
  802. var replaceOne = function(self, filter, doc, options, callback) {
  803. // Set single document update
  804. options.multi = false;
  805. // Execute update
  806. updateDocuments(self, filter, doc, options, function(err, r) {
  807. if (callback == null) return;
  808. if (err && callback) return callback(err);
  809. if (r == null) return callback(null, { result: { ok: 1 } });
  810. r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n;
  811. r.upsertedId =
  812. Array.isArray(r.result.upserted) && r.result.upserted.length > 0
  813. ? r.result.upserted[0]
  814. : null;
  815. r.upsertedCount =
  816. Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0;
  817. r.matchedCount =
  818. Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n;
  819. r.ops = [doc];
  820. if (callback) callback(null, r);
  821. });
  822. };
  823. define.classMethod('replaceOne', { callback: true, promise: true });
  824. /**
  825. * Update multiple documents on MongoDB
  826. * @method
  827. * @param {object} filter The Filter used to select the documents to update
  828. * @param {object} update The update operations to be applied to the document
  829. * @param {object} [options=null] Optional settings.
  830. * @param {boolean} [options.upsert=false] Update operation is an upsert.
  831. * @param {(number|string)} [options.w=null] The write concern.
  832. * @param {number} [options.wtimeout=null] The write concern timeout.
  833. * @param {boolean} [options.j=false] Specify a journal write concern.
  834. * @param {Array} [options.arrayFilters=null] optional list of array filters referenced in filtered positional operators
  835. * @param {ClientSession} [options.session] optional session to use for this operation
  836. * @param {Collection~updateWriteOpCallback} [callback] The command result callback
  837. * @return {Promise} returns Promise if no callback passed
  838. */
  839. Collection.prototype.updateMany = function(filter, update, options, callback) {
  840. if (typeof options === 'function') (callback = options), (options = {});
  841. options = options || {};
  842. var err = checkForAtomicOperators(update);
  843. if (err) {
  844. if (typeof callback === 'function') return callback(err);
  845. return this.s.promiseLibrary.reject(err);
  846. }
  847. options = shallowClone(options);
  848. // Add ignoreUndfined
  849. if (this.s.options.ignoreUndefined) {
  850. options = shallowClone(options);
  851. options.ignoreUndefined = this.s.options.ignoreUndefined;
  852. }
  853. return executeOperation(this.s.topology, updateMany, [this, filter, update, options, callback]);
  854. };
  855. var updateMany = function(self, filter, update, options, callback) {
  856. // Set single document update
  857. options.multi = true;
  858. // Execute update
  859. updateDocuments(self, filter, update, options, function(err, r) {
  860. if (callback == null) return;
  861. if (err && callback) return callback(err);
  862. if (r == null) return callback(null, { result: { ok: 1 } });
  863. r.modifiedCount = r.result.nModified != null ? r.result.nModified : r.result.n;
  864. r.upsertedId =
  865. Array.isArray(r.result.upserted) && r.result.upserted.length > 0
  866. ? r.result.upserted[0]
  867. : null;
  868. r.upsertedCount =
  869. Array.isArray(r.result.upserted) && r.result.upserted.length ? r.result.upserted.length : 0;
  870. r.matchedCount =
  871. Array.isArray(r.result.upserted) && r.result.upserted.length > 0 ? 0 : r.result.n;
  872. if (callback) callback(null, r);
  873. });
  874. };
  875. define.classMethod('updateMany', { callback: true, promise: true });
  876. var updateDocuments = function(self, selector, document, options, callback) {
  877. if ('function' === typeof options) (callback = options), (options = null);
  878. if (options == null) options = {};
  879. if (!('function' === typeof callback)) callback = null;
  880. // If we are not providing a selector or document throw
  881. if (selector == null || typeof selector !== 'object')
  882. return callback(toError('selector must be a valid JavaScript object'));
  883. if (document == null || typeof document !== 'object')
  884. return callback(toError('document must be a valid JavaScript object'));
  885. // Get the write concern options
  886. var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options);
  887. // Do we return the actual result document
  888. // Either use override on the function, or go back to default on either the collection
  889. // level or db
  890. finalOptions['serializeFunctions'] = options['serializeFunctions'] || self.s.serializeFunctions;
  891. // Execute the operation
  892. var op = { q: selector, u: document };
  893. op.upsert = options.upsert !== void 0 ? !!options.upsert : false;
  894. op.multi = options.multi !== void 0 ? !!options.multi : false;
  895. if (finalOptions.arrayFilters) {
  896. op.arrayFilters = finalOptions.arrayFilters;
  897. delete finalOptions.arrayFilters;
  898. }
  899. // Have we specified collation
  900. decorateWithCollation(finalOptions, self, options);
  901. // Update options
  902. self.s.topology.update(self.s.namespace, [op], finalOptions, function(err, result) {
  903. if (callback == null) return;
  904. if (err) return handleCallback(callback, err, null);
  905. if (result == null) return handleCallback(callback, null, null);
  906. if (result.result.code) return handleCallback(callback, toError(result.result));
  907. if (result.result.writeErrors)
  908. return handleCallback(callback, toError(result.result.writeErrors[0]));
  909. // Return the results
  910. handleCallback(callback, null, result);
  911. });
  912. };
  913. /**
  914. * Updates documents.
  915. * @method
  916. * @param {object} selector The selector for the update operation.
  917. * @param {object} document The update document.
  918. * @param {object} [options=null] Optional settings.
  919. * @param {(number|string)} [options.w=null] The write concern.
  920. * @param {number} [options.wtimeout=null] The write concern timeout.
  921. * @param {boolean} [options.j=false] Specify a journal write concern.
  922. * @param {boolean} [options.upsert=false] Update operation is an upsert.
  923. * @param {boolean} [options.multi=false] Update one/all documents with operation.
  924. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher.
  925. * @param {object} [options.collation=null] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields).
  926. * @param {Array} [options.arrayFilters=null] optional list of array filters referenced in filtered positional operators
  927. * @param {ClientSession} [options.session] optional session to use for this operation
  928. * @param {Collection~writeOpCallback} [callback] The command result callback
  929. * @throws {MongoError}
  930. * @return {Promise} returns Promise if no callback passed
  931. * @deprecated use updateOne, updateMany or bulkWrite
  932. */
  933. Collection.prototype.update = function(selector, document, options, callback) {
  934. if (typeof options === 'function') (callback = options), (options = {});
  935. options = options || {};
  936. // Add ignoreUndfined
  937. if (this.s.options.ignoreUndefined) {
  938. options = shallowClone(options);
  939. options.ignoreUndefined = this.s.options.ignoreUndefined;
  940. }
  941. return executeOperation(this.s.topology, updateDocuments, [
  942. this,
  943. selector,
  944. document,
  945. options,
  946. callback
  947. ]);
  948. };
  949. define.classMethod('update', { callback: true, promise: true });
  950. /**
  951. * @typedef {Object} Collection~deleteWriteOpResult
  952. * @property {Object} result The raw result returned from MongoDB, field will vary depending on server version.
  953. * @property {Number} result.ok Is 1 if the command executed correctly.
  954. * @property {Number} result.n The total count of documents deleted.
  955. * @property {Object} connection The connection object used for the operation.
  956. * @property {Number} deletedCount The number of documents deleted.
  957. */
  958. /**
  959. * The callback format for inserts
  960. * @callback Collection~deleteWriteOpCallback
  961. * @param {MongoError} error An error instance representing the error during the execution.
  962. * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully.
  963. */
  964. /**
  965. * Delete a document on MongoDB
  966. * @method
  967. * @param {object} filter The Filter used to select the document to remove
  968. * @param {object} [options=null] Optional settings.
  969. * @param {(number|string)} [options.w=null] The write concern.
  970. * @param {number} [options.wtimeout=null] The write concern timeout.
  971. * @param {boolean} [options.j=false] Specify a journal write concern.
  972. * @param {ClientSession} [options.session] optional session to use for this operation
  973. * @param {Collection~deleteWriteOpCallback} [callback] The command result callback
  974. * @return {Promise} returns Promise if no callback passed
  975. */
  976. Collection.prototype.deleteOne = function(filter, options, callback) {
  977. if (typeof options === 'function') (callback = options), (options = {});
  978. options = shallowClone(options);
  979. // Add ignoreUndfined
  980. if (this.s.options.ignoreUndefined) {
  981. options = shallowClone(options);
  982. options.ignoreUndefined = this.s.options.ignoreUndefined;
  983. }
  984. return executeOperation(this.s.topology, deleteOne, [this, filter, options, callback]);
  985. };
  986. var deleteOne = function(self, filter, options, callback) {
  987. options.single = true;
  988. removeDocuments(self, filter, options, function(err, r) {
  989. if (callback == null) return;
  990. if (err && callback) return callback(err);
  991. if (r == null) return callback(null, { result: { ok: 1 } });
  992. r.deletedCount = r.result.n;
  993. if (callback) callback(null, r);
  994. });
  995. };
  996. define.classMethod('deleteOne', { callback: true, promise: true });
  997. Collection.prototype.removeOne = Collection.prototype.deleteOne;
  998. define.classMethod('removeOne', { callback: true, promise: true });
  999. /**
  1000. * Delete multiple documents on MongoDB
  1001. * @method
  1002. * @param {object} filter The Filter used to select the documents to remove
  1003. * @param {object} [options=null] Optional settings.
  1004. * @param {(number|string)} [options.w=null] The write concern.
  1005. * @param {number} [options.wtimeout=null] The write concern timeout.
  1006. * @param {boolean} [options.j=false] Specify a journal write concern.
  1007. * @param {ClientSession} [options.session] optional session to use for this operation
  1008. * @param {Collection~deleteWriteOpCallback} [callback] The command result callback
  1009. * @return {Promise} returns Promise if no callback passed
  1010. */
  1011. Collection.prototype.deleteMany = function(filter, options, callback) {
  1012. if (typeof options === 'function') (callback = options), (options = {});
  1013. options = shallowClone(options);
  1014. // Add ignoreUndfined
  1015. if (this.s.options.ignoreUndefined) {
  1016. options = shallowClone(options);
  1017. options.ignoreUndefined = this.s.options.ignoreUndefined;
  1018. }
  1019. return executeOperation(this.s.topology, deleteMany, [this, filter, options, callback]);
  1020. };
  1021. var deleteMany = function(self, filter, options, callback) {
  1022. options.single = false;
  1023. removeDocuments(self, filter, options, function(err, r) {
  1024. if (callback == null) return;
  1025. if (err && callback) return callback(err);
  1026. if (r == null) return callback(null, { result: { ok: 1 } });
  1027. r.deletedCount = r.result.n;
  1028. if (callback) callback(null, r);
  1029. });
  1030. };
  1031. var removeDocuments = function(self, selector, options, callback) {
  1032. if (typeof options === 'function') {
  1033. (callback = options), (options = {});
  1034. } else if (typeof selector === 'function') {
  1035. callback = selector;
  1036. options = {};
  1037. selector = {};
  1038. }
  1039. // Create an empty options object if the provided one is null
  1040. options = options || {};
  1041. // Get the write concern options
  1042. var finalOptions = writeConcern(shallowClone(options), self.s.db, self, options);
  1043. // If selector is null set empty
  1044. if (selector == null) selector = {};
  1045. // Build the op
  1046. var op = { q: selector, limit: 0 };
  1047. if (options.single) op.limit = 1;
  1048. // Have we specified collation
  1049. decorateWithCollation(finalOptions, self, options);
  1050. // Execute the remove
  1051. self.s.topology.remove(self.s.namespace, [op], finalOptions, function(err, result) {
  1052. if (callback == null) return;
  1053. if (err) return handleCallback(callback, err, null);
  1054. if (result == null) return handleCallback(callback, null, null);
  1055. if (result.result.code) return handleCallback(callback, toError(result.result));
  1056. if (result.result.writeErrors)
  1057. return handleCallback(callback, toError(result.result.writeErrors[0]));
  1058. // Return the results
  1059. handleCallback(callback, null, result);
  1060. });
  1061. };
  1062. define.classMethod('deleteMany', { callback: true, promise: true });
  1063. Collection.prototype.removeMany = Collection.prototype.deleteMany;
  1064. define.classMethod('removeMany', { callback: true, promise: true });
  1065. /**
  1066. * Remove documents.
  1067. * @method
  1068. * @param {object} selector The selector for the update operation.
  1069. * @param {object} [options=null] Optional settings.
  1070. * @param {(number|string)} [options.w=null] The write concern.
  1071. * @param {number} [options.wtimeout=null] The write concern timeout.
  1072. * @param {boolean} [options.j=false] Specify a journal write concern.
  1073. * @param {boolean} [options.single=false] Removes the first document found.
  1074. * @param {ClientSession} [options.session] optional session to use for this operation
  1075. * @param {Collection~writeOpCallback} [callback] The command result callback
  1076. * @return {Promise} returns Promise if no callback passed
  1077. * @deprecated use deleteOne, deleteMany or bulkWrite
  1078. */
  1079. Collection.prototype.remove = function(selector, options, callback) {
  1080. if (typeof options === 'function') (callback = options), (options = {});