UNPKG

e-commercee

Version:

This package contains a backend of what would be the logic of a e-commercee software, the architecture used is made in 3 layers

1,053 lines (947 loc) 107 kB
'use strict'; const deprecate = require('util').deprecate; const deprecateOptions = require('./utils').deprecateOptions; const checkCollectionName = require('./utils').checkCollectionName; const ObjectID = require('./core').BSON.ObjectID; const MongoError = require('./core').MongoError; const normalizeHintField = require('./utils').normalizeHintField; const decorateCommand = require('./utils').decorateCommand; const decorateWithCollation = require('./utils').decorateWithCollation; const decorateWithReadConcern = require('./utils').decorateWithReadConcern; const formattedOrderClause = require('./utils').formattedOrderClause; const ReadPreference = require('./core').ReadPreference; const unordered = require('./bulk/unordered'); const ordered = require('./bulk/ordered'); const ChangeStream = require('./change_stream'); const executeLegacyOperation = require('./utils').executeLegacyOperation; const WriteConcern = require('./write_concern'); const ReadConcern = require('./read_concern'); const MongoDBNamespace = require('./utils').MongoDBNamespace; const AggregationCursor = require('./aggregation_cursor'); const CommandCursor = require('./command_cursor'); // Operations const ensureIndex = require('./operations/collection_ops').ensureIndex; const group = require('./operations/collection_ops').group; const parallelCollectionScan = require('./operations/collection_ops').parallelCollectionScan; const removeDocuments = require('./operations/common_functions').removeDocuments; const save = require('./operations/collection_ops').save; const updateDocuments = require('./operations/common_functions').updateDocuments; const AggregateOperation = require('./operations/aggregate'); const BulkWriteOperation = require('./operations/bulk_write'); const CountDocumentsOperation = require('./operations/count_documents'); const CreateIndexesOperation = require('./operations/create_indexes'); const DeleteManyOperation = require('./operations/delete_many'); const DeleteOneOperation = require('./operations/delete_one'); const DistinctOperation = require('./operations/distinct'); const DropCollectionOperation = require('./operations/drop').DropCollectionOperation; const DropIndexOperation = require('./operations/drop_index'); const DropIndexesOperation = require('./operations/drop_indexes'); const EstimatedDocumentCountOperation = require('./operations/estimated_document_count'); const FindOperation = require('./operations/find'); const FindOneOperation = require('./operations/find_one'); const FindAndModifyOperation = require('./operations/find_and_modify'); const FindOneAndDeleteOperation = require('./operations/find_one_and_delete'); const FindOneAndReplaceOperation = require('./operations/find_one_and_replace'); const FindOneAndUpdateOperation = require('./operations/find_one_and_update'); const GeoHaystackSearchOperation = require('./operations/geo_haystack_search'); const IndexesOperation = require('./operations/indexes'); const IndexExistsOperation = require('./operations/index_exists'); const IndexInformationOperation = require('./operations/index_information'); const InsertManyOperation = require('./operations/insert_many'); const InsertOneOperation = require('./operations/insert_one'); const IsCappedOperation = require('./operations/is_capped'); const ListIndexesOperation = require('./operations/list_indexes'); const MapReduceOperation = require('./operations/map_reduce'); const OptionsOperation = require('./operations/options_operation'); const RenameOperation = require('./operations/rename'); const ReIndexOperation = require('./operations/re_index'); const ReplaceOneOperation = require('./operations/replace_one'); const StatsOperation = require('./operations/stats'); const UpdateManyOperation = require('./operations/update_many'); const UpdateOneOperation = require('./operations/update_one'); const executeOperation = require('./operations/execute_operation'); /** * @fileOverview The **Collection** class is an internal class that embodies a MongoDB collection * allowing for insert/update/remove/find and other command operation on that MongoDB collection. * * **COLLECTION Cannot directly be instantiated** * @example * const MongoClient = require('mongodb').MongoClient; * const test = require('assert'); * // Connection url * const url = 'mongodb://localhost:27017'; * // Database Name * const dbName = 'test'; * // Connect using MongoClient * MongoClient.connect(url, function(err, client) { * // Create a collection we want to drop later * const col = client.db(dbName).collection('createIndexExample1'); * // Show that duplicate records got dropped * col.find({}).toArray(function(err, items) { * test.equal(null, err); * test.equal(4, items.length); * client.close(); * }); * }); */ const mergeKeys = ['ignoreUndefined']; /** * Create a new Collection instance (INTERNAL TYPE, do not instantiate directly) * @class */ function Collection(db, topology, dbName, name, pkFactory, options) { checkCollectionName(name); // Unpack variables const internalHint = null; const slaveOk = options == null || options.slaveOk == null ? db.slaveOk : options.slaveOk; const serializeFunctions = options == null || options.serializeFunctions == null ? db.s.options.serializeFunctions : options.serializeFunctions; const raw = options == null || options.raw == null ? db.s.options.raw : options.raw; const promoteLongs = options == null || options.promoteLongs == null ? db.s.options.promoteLongs : options.promoteLongs; const promoteValues = options == null || options.promoteValues == null ? db.s.options.promoteValues : options.promoteValues; const promoteBuffers = options == null || options.promoteBuffers == null ? db.s.options.promoteBuffers : options.promoteBuffers; const collectionHint = null; const namespace = new MongoDBNamespace(dbName, name); // Get the promiseLibrary const promiseLibrary = options.promiseLibrary || Promise; // Set custom primary key factory if provided pkFactory = pkFactory == null ? ObjectID : pkFactory; // Internal state this.s = { // Set custom primary key factory if provided pkFactory: pkFactory, // Db db: db, // Topology topology: topology, // Options options: options, // Namespace namespace: namespace, // Read preference readPreference: ReadPreference.fromOptions(options), // SlaveOK slaveOk: slaveOk, // Serialize functions serializeFunctions: serializeFunctions, // Raw raw: raw, // promoteLongs promoteLongs: promoteLongs, // promoteValues promoteValues: promoteValues, // promoteBuffers promoteBuffers: promoteBuffers, // internalHint internalHint: internalHint, // collectionHint collectionHint: collectionHint, // Promise library promiseLibrary: promiseLibrary, // Read Concern readConcern: ReadConcern.fromOptions(options), // Write Concern writeConcern: WriteConcern.fromOptions(options) }; } /** * The name of the database this collection belongs to * @member {string} dbName * @memberof Collection# * @readonly */ Object.defineProperty(Collection.prototype, 'dbName', { enumerable: true, get: function() { return this.s.namespace.db; } }); /** * The name of this collection * @member {string} collectionName * @memberof Collection# * @readonly */ Object.defineProperty(Collection.prototype, 'collectionName', { enumerable: true, get: function() { return this.s.namespace.collection; } }); /** * The namespace of this collection, in the format `${this.dbName}.${this.collectionName}` * @member {string} namespace * @memberof Collection# * @readonly */ Object.defineProperty(Collection.prototype, 'namespace', { enumerable: true, get: function() { return this.s.namespace.toString(); } }); /** * The current readConcern of the collection. If not explicitly defined for * this collection, will be inherited from the parent DB * @member {ReadConcern} [readConcern] * @memberof Collection# * @readonly */ Object.defineProperty(Collection.prototype, 'readConcern', { enumerable: true, get: function() { if (this.s.readConcern == null) { return this.s.db.readConcern; } return this.s.readConcern; } }); /** * The current readPreference of the collection. If not explicitly defined for * this collection, will be inherited from the parent DB * @member {ReadPreference} [readPreference] * @memberof Collection# * @readonly */ Object.defineProperty(Collection.prototype, 'readPreference', { enumerable: true, get: function() { if (this.s.readPreference == null) { return this.s.db.readPreference; } return this.s.readPreference; } }); /** * The current writeConcern of the collection. If not explicitly defined for * this collection, will be inherited from the parent DB * @member {WriteConcern} [writeConcern] * @memberof Collection# * @readonly */ Object.defineProperty(Collection.prototype, 'writeConcern', { enumerable: true, get: function() { if (this.s.writeConcern == null) { return this.s.db.writeConcern; } return this.s.writeConcern; } }); /** * The current index hint for the collection * @member {object} [hint] * @memberof Collection# */ Object.defineProperty(Collection.prototype, 'hint', { enumerable: true, get: function() { return this.s.collectionHint; }, set: function(v) { this.s.collectionHint = normalizeHintField(v); } }); const DEPRECATED_FIND_OPTIONS = ['maxScan', 'fields', 'snapshot', 'oplogReplay']; /** * Creates a cursor for a query that can be used to iterate over results from MongoDB * @method * @param {object} [query={}] The cursor query object. * @param {object} [options] Optional settings. * @param {number} [options.limit=0] Sets the limit of documents returned in the query. * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. * @param {object} [options.projection] The fields to return in the query. Object of fields to either include or exclude (one of, not both), {'a':1, 'b': 1} **or** {'a': 0, 'b': 0} * @param {object} [options.fields] **Deprecated** Use `options.projection` instead * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} * @param {boolean} [options.explain=false] Explain the query instead of returning the data. * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. * @param {boolean} [options.awaitData=false] Specify if the cursor is a a tailable-await cursor. Requires `tailable` to be true * @param {number} [options.batchSize=1000] Set the batchSize for the getMoreCommand when iterating over the query results. * @param {boolean} [options.returnKey=false] Only return the index key. * @param {number} [options.maxScan] DEPRECATED: Limit the number of items to scan. * @param {number} [options.min] Set index bounds. * @param {number} [options.max] Set index bounds. * @param {boolean} [options.showDiskLoc=false] Show disk location of results. * @param {string} [options.comment] You can put a $comment field on a query to make looking in the profiler logs simpler. * @param {boolean} [options.raw=false] Return document results as raw BSON buffers. * @param {boolean} [options.promoteLongs=true] Promotes Long values to number if they fit inside the 53 bits resolution. * @param {boolean} [options.promoteValues=true] Promotes BSON values to native types where possible, set to false to only receive wrapper types. * @param {boolean} [options.promoteBuffers=false] Promotes Binary BSON values to native Node Buffers. * @param {(ReadPreference|string)} [options.readPreference] The preferred read preference (ReadPreference.PRIMARY, ReadPreference.PRIMARY_PREFERRED, ReadPreference.SECONDARY, ReadPreference.SECONDARY_PREFERRED, ReadPreference.NEAREST). * @param {boolean} [options.partial=false] Specify if the cursor should return partial results when querying against a sharded system * @param {number} [options.maxTimeMS] Number of milliseconds to wait before aborting the query. * @param {number} [options.maxAwaitTimeMS] The maximum amount of time for the server to wait on new documents to satisfy a tailable cursor query. Requires `tailable` and `awaitData` to be true * @param {boolean} [options.noCursorTimeout] The server normally times out idle cursors after an inactivity period (10 minutes) to prevent excess memory use. Set this option to prevent that. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). * @param {boolean} [options.allowDiskUse] Enables writing to temporary files on the server. * @param {ClientSession} [options.session] optional session to use for this operation * @throws {MongoError} * @return {Cursor} */ Collection.prototype.find = deprecateOptions( { name: 'collection.find', deprecatedOptions: DEPRECATED_FIND_OPTIONS, optionsIndex: 1 }, function(query, options, callback) { if (typeof callback === 'object') { // TODO(MAJOR): throw in the future console.warn('Third parameter to `find()` must be a callback or undefined'); } let selector = query; // figuring out arguments if (typeof callback !== 'function') { if (typeof options === 'function') { callback = options; options = undefined; } else if (options == null) { callback = typeof selector === 'function' ? selector : undefined; selector = typeof selector === 'object' ? selector : undefined; } } // Ensure selector is not null selector = selector == null ? {} : selector; // Validate correctness off the selector const object = selector; if (Buffer.isBuffer(object)) { const object_size = object[0] | (object[1] << 8) | (object[2] << 16) | (object[3] << 24); if (object_size !== object.length) { const error = new Error( 'query selector raw message size does not match message header size [' + object.length + '] != [' + object_size + ']' ); error.name = 'MongoError'; throw error; } } // Check special case where we are using an objectId if (selector != null && selector._bsontype === 'ObjectID') { selector = { _id: selector }; } if (!options) options = {}; let projection = options.projection || options.fields; if (projection && !Buffer.isBuffer(projection) && Array.isArray(projection)) { projection = projection.length ? projection.reduce((result, field) => { result[field] = 1; return result; }, {}) : { _id: 1 }; } // Make a shallow copy of options let newOptions = Object.assign({}, options); // Make a shallow copy of the collection options for (let key in this.s.options) { if (mergeKeys.indexOf(key) !== -1) { newOptions[key] = this.s.options[key]; } } // Unpack options newOptions.skip = options.skip ? options.skip : 0; newOptions.limit = options.limit ? options.limit : 0; newOptions.raw = typeof options.raw === 'boolean' ? options.raw : this.s.raw; newOptions.hint = options.hint != null ? normalizeHintField(options.hint) : this.s.collectionHint; newOptions.timeout = typeof options.timeout === 'undefined' ? undefined : options.timeout; // // If we have overridden slaveOk otherwise use the default db setting newOptions.slaveOk = options.slaveOk != null ? options.slaveOk : this.s.db.slaveOk; // Add read preference if needed newOptions.readPreference = ReadPreference.resolve(this, newOptions); // Set slave ok to true if read preference different from primary if ( newOptions.readPreference != null && (newOptions.readPreference !== 'primary' || newOptions.readPreference.mode !== 'primary') ) { newOptions.slaveOk = true; } // Ensure the query is an object if (selector != null && typeof selector !== 'object') { throw MongoError.create({ message: 'query selector must be an object', driver: true }); } // Build the find command const findCommand = { find: this.s.namespace.toString(), limit: newOptions.limit, skip: newOptions.skip, query: selector }; if (typeof options.allowDiskUse === 'boolean') { findCommand.allowDiskUse = options.allowDiskUse; } // Ensure we use the right await data option if (typeof newOptions.awaitdata === 'boolean') { newOptions.awaitData = newOptions.awaitdata; } // Translate to new command option noCursorTimeout if (typeof newOptions.timeout === 'boolean') newOptions.noCursorTimeout = newOptions.timeout; decorateCommand(findCommand, newOptions, ['session', 'collation']); if (projection) findCommand.fields = projection; // Add db object to the new options newOptions.db = this.s.db; // Add the promise library newOptions.promiseLibrary = this.s.promiseLibrary; // Set raw if available at collection level if (newOptions.raw == null && typeof this.s.raw === 'boolean') newOptions.raw = this.s.raw; // Set promoteLongs if available at collection level if (newOptions.promoteLongs == null && typeof this.s.promoteLongs === 'boolean') newOptions.promoteLongs = this.s.promoteLongs; if (newOptions.promoteValues == null && typeof this.s.promoteValues === 'boolean') newOptions.promoteValues = this.s.promoteValues; if (newOptions.promoteBuffers == null && typeof this.s.promoteBuffers === 'boolean') newOptions.promoteBuffers = this.s.promoteBuffers; // Sort options if (findCommand.sort) { findCommand.sort = formattedOrderClause(findCommand.sort); } // Set the readConcern decorateWithReadConcern(findCommand, this, options); // Decorate find command with collation options try { decorateWithCollation(findCommand, this, options); } catch (err) { if (typeof callback === 'function') return callback(err, null); throw err; } const cursor = this.s.topology.cursor( new FindOperation(this, this.s.namespace, findCommand, newOptions), newOptions ); // TODO: remove this when NODE-2074 is resolved if (typeof callback === 'function') { callback(null, cursor); return; } return cursor; } ); /** * Inserts a single document into MongoDB. If documents passed in do not contain the **_id** field, * one will be added to each of the documents missing it by the driver, mutating the document. This behavior * can be overridden by setting the **forceServerObjectId** flag. * * @method * @param {object} doc Document to insert. * @param {object} [options] Optional settings. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. * @param {(number|string)} [options.w] The write concern. * @param {number} [options.wtimeout] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.checkKeys=true] If true, will throw if bson documents start with `$` or include a `.` in any key value * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~insertOneWriteOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.insertOne = function(doc, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Add ignoreUndefined if (this.s.options.ignoreUndefined) { options = Object.assign({}, options); options.ignoreUndefined = this.s.options.ignoreUndefined; } const insertOneOperation = new InsertOneOperation(this, doc, options); return executeOperation(this.s.topology, insertOneOperation, callback); }; /** * Inserts an array of documents into MongoDB. If documents passed in do not contain the **_id** field, * one will be added to each of the documents missing it by the driver, mutating the document. This behavior * can be overridden by setting the **forceServerObjectId** flag. * * @method * @param {object[]} docs Documents to insert. * @param {object} [options] Optional settings. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. * @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. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. * @param {(number|string)} [options.w] The write concern. * @param {number} [options.wtimeout] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.checkKeys=true] If true, will throw if bson documents start with `$` or include a `.` in any key value * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~insertWriteOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.insertMany = function(docs, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options ? Object.assign({}, options) : { ordered: true }; const insertManyOperation = new InsertManyOperation(this, docs, options); return executeOperation(this.s.topology, insertManyOperation, callback); }; /** * @typedef {Object} Collection~BulkWriteOpResult * @property {number} insertedCount Number of documents inserted. * @property {number} matchedCount Number of documents matched for update. * @property {number} modifiedCount Number of documents modified. * @property {number} deletedCount Number of documents deleted. * @property {number} upsertedCount Number of documents upserted. * @property {object} insertedIds Inserted document generated Id's, hash key is the index of the originating operation * @property {object} upsertedIds Upserted document generated Id's, hash key is the index of the originating operation * @property {object} result The command result object. */ /** * The callback format for inserts * @callback Collection~bulkWriteOpCallback * @param {BulkWriteError} error An error instance representing the error during the execution. * @param {Collection~BulkWriteOpResult} result The result object if the command was executed successfully. */ /** * Perform a bulkWrite operation without a fluent API * * Legal operation types are * * { insertOne: { document: { a: 1 } } } * * { updateOne: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } * * { updateMany: { filter: {a:2}, update: {$set: {a:2}}, upsert:true } } * * { updateMany: { filter: {}, update: {$set: {"a.$[i].x": 5}}, arrayFilters: [{ "i.x": 5 }]} } * * { deleteOne: { filter: {c:1} } } * * { deleteMany: { filter: {c:1} } } * * { replaceOne: { filter: {c:3}, replacement: {c:4}, upsert:true}} * * If documents passed in do not contain the **_id** field, * one will be added to each of the documents missing it by the driver, mutating the document. This behavior * can be overridden by setting the **forceServerObjectId** flag. * * @method * @param {object[]} operations Bulk operations to perform. * @param {object} [options] Optional settings. * @param {boolean} [options.ordered=true] Execute write operation in ordered or unordered fashion. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. * @param {object[]} [options.arrayFilters] Determines which array elements to modify for update operation in MongoDB 3.6 or higher. * @param {(number|string)} [options.w] The write concern. * @param {number} [options.wtimeout] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~bulkWriteOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.bulkWrite = function(operations, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || { ordered: true }; if (!Array.isArray(operations)) { throw MongoError.create({ message: 'operations must be an array of documents', driver: true }); } const bulkWriteOperation = new BulkWriteOperation(this, operations, options); return executeOperation(this.s.topology, bulkWriteOperation, callback); }; /** * @typedef {Object} Collection~WriteOpResult * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany * @property {object} connection The connection object used for the operation. * @property {object} result The command result object. */ /** * The callback format for inserts * @callback Collection~writeOpCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {Collection~WriteOpResult} result The result object if the command was executed successfully. */ /** * @typedef {Object} Collection~insertWriteOpResult * @property {number} insertedCount The total amount of documents inserted. * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany * @property {Object.<Number, ObjectId>} insertedIds Map of the index of the inserted document to the id of the inserted document. * @property {object} connection The connection object used for the operation. * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). * @property {number} result.ok Is 1 if the command executed correctly. * @property {number} result.n The total count of documents inserted. */ /** * @typedef {Object} Collection~insertOneWriteOpResult * @property {number} insertedCount The total amount of documents inserted. * @property {object[]} ops All the documents inserted using insertOne/insertMany/replaceOne. Documents contain the _id field if forceServerObjectId == false for insertOne/insertMany * @property {ObjectId} insertedId The driver generated ObjectId for the insert operation. * @property {object} connection The connection object used for the operation. * @property {object} result The raw command result object returned from MongoDB (content might vary by server version). * @property {number} result.ok Is 1 if the command executed correctly. * @property {number} result.n The total count of documents inserted. */ /** * The callback format for inserts * @callback Collection~insertWriteOpCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {Collection~insertWriteOpResult} result The result object if the command was executed successfully. */ /** * The callback format for inserts * @callback Collection~insertOneWriteOpCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {Collection~insertOneWriteOpResult} result The result object if the command was executed successfully. */ /** * Inserts a single document or a an array of documents into MongoDB. If documents passed in do not contain the **_id** field, * one will be added to each of the documents missing it by the driver, mutating the document. This behavior * can be overridden by setting the **forceServerObjectId** flag. * * @method * @param {(object|object[])} docs Documents to insert. * @param {object} [options] Optional settings. * @param {(number|string)} [options.w] The write concern. * @param {number} [options.wtimeout] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. * @param {boolean} [options.forceServerObjectId=false] Force server to assign _id values instead of driver. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~insertWriteOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed * @deprecated Use insertOne, insertMany or bulkWrite */ Collection.prototype.insert = deprecate(function(docs, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || { ordered: false }; docs = !Array.isArray(docs) ? [docs] : docs; if (options.keepGoing === true) { options.ordered = false; } return this.insertMany(docs, options, callback); }, 'collection.insert is deprecated. Use insertOne, insertMany or bulkWrite instead.'); /** * @typedef {Object} Collection~updateWriteOpResult * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. * @property {Number} result.ok Is 1 if the command executed correctly. * @property {Number} result.n The total count of documents scanned. * @property {Number} result.nModified The total count of documents modified. * @property {Object} connection The connection object used for the operation. * @property {Number} matchedCount The number of documents that matched the filter. * @property {Number} modifiedCount The number of documents that were modified. * @property {Number} upsertedCount The number of documents upserted. * @property {Object} upsertedId The upserted id. * @property {ObjectId} upsertedId._id The upserted _id returned from the server. * @property {Object} message The raw msg response wrapped in an internal class * @property {object[]} [ops] In a response to {@link Collection#replaceOne replaceOne}, contains the new value of the document on the server. This is the same document that was originally passed in, and is only here for legacy purposes. */ /** * The callback format for inserts * @callback Collection~updateWriteOpCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {Collection~updateWriteOpResult} result The result object if the command was executed successfully. */ /** * Update a single document in a collection * @method * @param {object} filter The Filter used to select the document to update * @param {object} update The update operations to be applied to the document * @param {object} [options] Optional settings. * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query.. * @param {(number|string)} [options.w] The write concern. * @param {number} [options.wtimeout] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~updateWriteOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.updateOne = function(filter, update, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = Object.assign({}, options); // Add ignoreUndefined if (this.s.options.ignoreUndefined) { options = Object.assign({}, options); options.ignoreUndefined = this.s.options.ignoreUndefined; } return executeOperation( this.s.topology, new UpdateOneOperation(this, filter, update, options), callback ); }; /** * Replace a document in a collection with another document * @method * @param {object} filter The Filter used to select the document to replace * @param {object} doc The Document that replaces the matching document * @param {object} [options] Optional settings. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query. * @param {(number|string)} [options.w] The write concern. * @param {number} [options.wtimeout] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~updateWriteOpCallback} [callback] The command result callback * @return {Promise<Collection~updateWriteOpResult>} returns Promise if no callback passed */ Collection.prototype.replaceOne = function(filter, doc, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = Object.assign({}, options); // Add ignoreUndefined if (this.s.options.ignoreUndefined) { options = Object.assign({}, options); options.ignoreUndefined = this.s.options.ignoreUndefined; } return executeOperation( this.s.topology, new ReplaceOneOperation(this, filter, doc, options), callback ); }; /** * Update multiple documents in a collection * @method * @param {object} filter The Filter used to select the documents to update * @param {object} update The update operations to be applied to the documents * @param {object} [options] Optional settings. * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. * @param {boolean} [options.upsert=false] When true, creates a new document if no document matches the query.. * @param {(number|string)} [options.w] The write concern. * @param {number} [options.wtimeout] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~updateWriteOpCallback} [callback] The command result callback * @return {Promise<Collection~updateWriteOpResult>} returns Promise if no callback passed */ Collection.prototype.updateMany = function(filter, update, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = Object.assign({}, options); // Add ignoreUndefined if (this.s.options.ignoreUndefined) { options = Object.assign({}, options); options.ignoreUndefined = this.s.options.ignoreUndefined; } return executeOperation( this.s.topology, new UpdateManyOperation(this, filter, update, options), callback ); }; /** * Updates documents. * @method * @param {object} selector The selector for the update operation. * @param {object} update The update operations to be applied to the documents * @param {object} [options] Optional settings. * @param {(number|string)} [options.w] The write concern. * @param {number} [options.wtimeout] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.upsert=false] Update operation is an upsert. * @param {boolean} [options.multi=false] Update one/all documents with operation. * @param {boolean} [options.bypassDocumentValidation=false] Allow driver to bypass schema validation in MongoDB 3.2 or higher. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). * @param {Array} [options.arrayFilters] optional list of array filters referenced in filtered positional operators * @param {ClientSession} [options.session] optional session to use for this operation * @param {object} [options.hint] An optional hint for query optimization. See the {@link https://docs.mongodb.com/manual/reference/command/update/#update-command-hint|update command} reference for more information. * @param {Collection~writeOpCallback} [callback] The command result callback * @throws {MongoError} * @return {Promise} returns Promise if no callback passed * @deprecated use updateOne, updateMany or bulkWrite */ Collection.prototype.update = deprecate(function(selector, update, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Add ignoreUndefined if (this.s.options.ignoreUndefined) { options = Object.assign({}, options); options.ignoreUndefined = this.s.options.ignoreUndefined; } return executeLegacyOperation(this.s.topology, updateDocuments, [ this, selector, update, options, callback ]); }, 'collection.update is deprecated. Use updateOne, updateMany, or bulkWrite instead.'); /** * @typedef {Object} Collection~deleteWriteOpResult * @property {Object} result The raw result returned from MongoDB. Will vary depending on server version. * @property {Number} result.ok Is 1 if the command executed correctly. * @property {Number} result.n The total count of documents deleted. * @property {Object} connection The connection object used for the operation. * @property {Number} deletedCount The number of documents deleted. */ /** * The callback format for deletes * @callback Collection~deleteWriteOpCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {Collection~deleteWriteOpResult} result The result object if the command was executed successfully. */ /** * Delete a document from a collection * @method * @param {object} filter The Filter used to select the document to remove * @param {object} [options] Optional settings. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). * @param {(number|string)} [options.w] The write concern. * @param {number} [options.wtimeout] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session] optional session to use for this operation * @param {string|object} [options.hint] optional index hint for optimizing the filter query * @param {Collection~deleteWriteOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.deleteOne = function(filter, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = Object.assign({}, options); // Add ignoreUndefined if (this.s.options.ignoreUndefined) { options = Object.assign({}, options); options.ignoreUndefined = this.s.options.ignoreUndefined; } const deleteOneOperation = new DeleteOneOperation(this, filter, options); return executeOperation(this.s.topology, deleteOneOperation, callback); }; Collection.prototype.removeOne = Collection.prototype.deleteOne; /** * Delete multiple documents from a collection * @method * @param {object} filter The Filter used to select the documents to remove * @param {object} [options] Optional settings. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). * @param {(number|string)} [options.w] The write concern. * @param {number} [options.wtimeout] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.checkKeys=false] If true, will throw if bson documents start with `$` or include a `.` in any key value * @param {boolean} [options.serializeFunctions=false] Serialize functions on any object. * @param {boolean} [options.ignoreUndefined=false] Specify if the BSON serializer should ignore undefined fields. * @param {ClientSession} [options.session] optional session to use for this operation * @param {string|object} [options.hint] optional index hint for optimizing the filter query * @param {Collection~deleteWriteOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed */ Collection.prototype.deleteMany = function(filter, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = Object.assign({}, options); // Add ignoreUndefined if (this.s.options.ignoreUndefined) { options = Object.assign({}, options); options.ignoreUndefined = this.s.options.ignoreUndefined; } const deleteManyOperation = new DeleteManyOperation(this, filter, options); return executeOperation(this.s.topology, deleteManyOperation, callback); }; Collection.prototype.removeMany = Collection.prototype.deleteMany; /** * Remove documents. * @method * @param {object} selector The selector for the update operation. * @param {object} [options] Optional settings. * @param {object} [options.collation] Specify collation (MongoDB 3.4 or higher) settings for update operation (see 3.4 documentation for available fields). * @param {(number|string)} [options.w] The write concern. * @param {number} [options.wtimeout] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {boolean} [options.single=false] Removes the first document found. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~writeOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed * @deprecated use deleteOne, deleteMany or bulkWrite */ Collection.prototype.remove = deprecate(function(selector, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Add ignoreUndefined if (this.s.options.ignoreUndefined) { options = Object.assign({}, options); options.ignoreUndefined = this.s.options.ignoreUndefined; } return executeLegacyOperation(this.s.topology, removeDocuments, [ this, selector, options, callback ]); }, 'collection.remove is deprecated. Use deleteOne, deleteMany, or bulkWrite instead.'); /** * Save a document. Simple full document replacement function. Not recommended for efficiency, use atomic * operators and update instead for more efficient operations. * @method * @param {object} doc Document to save * @param {object} [options] Optional settings. * @param {(number|string)} [options.w] The write concern. * @param {number} [options.wtimeout] The write concern timeout. * @param {boolean} [options.j=false] Specify a journal write concern. * @param {ClientSession} [options.session] optional session to use for this operation * @param {Collection~writeOpCallback} [callback] The command result callback * @return {Promise} returns Promise if no callback passed * @deprecated use insertOne, insertMany, updateOne or updateMany */ Collection.prototype.save = deprecate(function(doc, options, callback) { if (typeof options === 'function') (callback = options), (options = {}); options = options || {}; // Add ignoreUndefined if (this.s.options.ignoreUndefined) { options = Object.assign({}, options); options.ignoreUndefined = this.s.options.ignoreUndefined; } return executeLegacyOperation(this.s.topology, save, [this, doc, options, callback]); }, 'collection.save is deprecated. Use insertOne, insertMany, updateOne, or updateMany instead.'); /** * The callback format for results * @callback Collection~resultCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {object} result The result object if the command was executed successfully. */ /** * The callback format for an aggregation call * @callback Collection~aggregationCallback * @param {MongoError} error An error instance representing the error during the execution. * @param {AggregationCursor} cursor The cursor if the aggregation command was executed successfully. */ /** * Fetches the first document that matches the query * @method * @param {object} query Query for find Operation * @param {object} [options] Optional settings. * @param {number} [options.limit=0] Sets the limit of documents returned in the query. * @param {(array|object)} [options.sort] Set to sort the documents coming back from the query. Array of indexes, [['a', 1]] etc. * @param {object} [options.projection] The fields to return in the query. Object of fields to include or exclude (not both), {'a':1} * @param {object} [options.fields] **Deprecated** Use `options.projection` instead * @param {number} [options.skip=0] Set to skip N documents ahead in your query (useful for pagination). * @param {Object} [options.hint] Tell the query to use specific indexes in the query. Object of indexes to use, {'_id':1} * @param {boolean} [options.explain=false] Explain the query instead of returning the data. * @param {boolean} [options.snapshot=false] DEPRECATED: Snapshot query. * @param {boolean} [options.timeout=false] Specify if the cursor can timeout. * @param {boolean} [options.tailable=false] Specify if the cursor is tailable. * @param {number} [options.batchSize=1] Set the batchSize for the getMoreCommand when iterating over the query results. * @param {boolean} [options.returnKey=false] Only return the index key. * @param {n