npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

mongodbext

v5.0.1

Published

Extension for node-mongodb-native that allows to add hooks on write operations, such as create, update, remove

Readme

mongodbext

Build Status

This is extension for node-mongodb-native that imports patched collection object and allows to add hooks on write operations, such as insert, update and delete. It also adds some options to this operations, that allows to modify operation's result.

Important since version 3.0.0 mongodb drivers of versions 2.x.x are no longer supported.

Installation

npm install mongodbext

Usage

new Collection(db, collectionName, options)

Creates new instance of collection

Parameters:

All parameters described as name, type, default value.

  • db, object. Database instance

  • collectionName, string. Name of collection.

  • options, object, null. Optional settings.

    • changeDataMethods, Array, null. Set supported data changing methods. If not set all methods are supported.
    • customCountImplementation, boolean, null. Starting from 4.0 MongoDB deprecates count method in favor of countDocuments and estimatedDocumentCount. Setting customCountImplementation to true allows you to use under the hood of count either countDocuments if query predicate exists or estimatedDocumentCount if no query predicate provided.
Returns:

Instance of collection

Examples:
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'constructorExample');

	collection.insertOne({a: 1}, function(err) {
		expect(err).not.ok();
	});
});
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'constructorExample', {
		changeDataMethods: ['insertMany']
	});

	collection.insertOne({a: 1}, function(err) {
		expect(err).ok();
		expect(err.name).equal('MongoError');
		expect(err.message).equal('Method "insertOne" for collection "test" is not supported');
	});
});

Collection methods

Methods marked as deprecated are not present in documentation.

deleteMany(filter, options, callback)

Delete multiple documents on MongoDB

Parameters:

All parameters described as name, type, default value.

  • filter, object. The Filter used to select the documents to remove

  • options, object, null. Optional settings.

    • w, number or string, null. The write concern.

    • wtimeout, number, null. The write concern timeout.

    • j, boolean, false. Specify a journal write concern.

    • returnResultOnly, boolean, true. Specifying result returning in callback.

  • callback, function. The command result callback

Returns:

Promise if no callback passed

Examples:

var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'deleteManyExample');

	collection.insertMany([{
		a: 1
	}, {
		a: 2
	}], function(err, insertResult) {
		collection.deleteMany({}, function(err, deleteManyResult) {
			expect(deleteManyResult).only.keys('deletedCount');
		});
	});
});
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'deleteManyExample');

	collection.insertMany([{
		a: 1
	}, {
		a: 2
	}], function(err, insertResult) {
		collection.deleteMany({}, {
			returnDocsOnly: false
		}, function(err, deleteManyResult) {
			expect(deleteManyResult).only.keys(
				'connection', 'result', 'deletedCount'
			);
		});
	});
});

deleteOne(filter, options, callback)

Delete a document on MongoDB

Parameters:

All parameters described as name, type, default value.

  • filter, object. The Filter used to select the documents to remove

  • options, object, null. Optional settings.

    • w, number or string, null. The write concern.

    • wtimeout, number, null. The write concern timeout.

    • j, boolean, false. Specify a journal write concern.

    • bypassDocumentValidation, boolean, false. Allow driver to bypass schema validation in MongoDB 3.2 or higher.

    • returnResultOnly, boolean, true. Specifying result returning in callback.

  • callback, function. The command result callback

Returns:

Promise if no callback passed

Examples:

var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'deleteOneExample');

	collection.insertOne({
		a: 1
	}, function(err, insertResult) {
		collection.deleteOne({}, function(err, deleteOneResult) {
			expect(deleteOneResult).only.keys('deletedCount');
		});
	});
});
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'deleteOneExample');

	collection.insertOne({
		a: 1
	}, function(err, insertResult) {
		collection.deleteOne({}, {
			returnDocsOnly: false
		}, function(err, deleteOneResult) {
			expect(deleteOneResult).only.keys(
				'connection', 'result', 'deletedCount'
			);
		});
	});
});

find(query, projection)

Creates a cursor for a query that can be used to iterate over results from MongoDB

Parameters:

All parameters described as name, type, default value.

  • filter, object. The Cursor query object.

  • projection, object, null. The field projection object.

Returns:

Cursor

Examples:
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'findExample');

	collection.insertMany([{
		a: 1
	}, {
		a: 2
	}], function(err, insertResult) {
		collection.find({}, {
			_id: 0
		}).toArray(function(err, findResult) {
			findResult.forEach(function(obj) {
				expect(obj).not.key('_id');
			});
		});
	});
});

findOne(query, projection, callback)

Fetches the first document that matches the query

Parameters:

All parameters described as name, type, default value.

  • filter, object. Query for find Operation.

  • projection, object, null. The field projection object.

  • callback, function. The command result callback

Returns:

Promise if no callback passed

Examples:
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'findOneExample');

	collection.insertOne({
		a: 1
	}, function(err, insertResult) {
		collection.findOne({}, {
			_id: 0
		}, function(err, findOneResult) {
			expect(findOneResult).eql({a: 1});
		});
	});
});

findOneAndDelete(filter, options, callback)

Find a document and delete it in one atomic operation, requires a write lock for the duration of the operation.

Parameters:

All parameters described as name, type, default value.

  • filter, object. Document selection filter.

  • options, object, null. Optional settings.

    • projection, object, null. Limits the fields to return for all matching documents.

    • sort, object, null. Determines which document the operation modifies if the query selects multiple documents.

    • maxTimeMS, number, null. The maximum amount of time to allow the query to run.

    • returnDocsOnly, boolean, true. When true returns only result document.

  • callback, function. The collection result callback.

Returns:

Promise if no callback passed

Examples:
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'findOneAndDeleteExample');

	collection.insertOne({
		a: 1
	}, function(err, insertResult) {
		collection.findOneAndDelete({
			_id: insertResult._id
		}, function(err, deleteResult) {
			expect(deleteResult).eql(insertResult);
		});
	});
});
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'findOneAndDeleteExample');

	collection.insertOne({
		a: 1
	}, function(err, insertResult) {
		collection.findOneAndDelete({
			_id: insertResult._id
		}, {
			returnDocsOnly: false
		}, function(err, deleteResult) {
			expect(deleteResult).keys(
				'value', 'ok', 'lastErrorObject'
			);
		});
	});
});

findOneAndReplace(filter, replacement, options, callback)

Find a document and replace it in one atomic operation, requires a write lock for the duration of the operation.

Parameters:

All parameters described as name, type, default value.

  • filter, object. Document selection filter.

  • replacement, object. Document replacing the matching document.

  • options, object, null. Optional settings.

    • projection, object, null. Limits the fields to return for all matching documents.

    • sort, object, null. Determines which document the operation modifies if the query selects multiple documents.

    • maxTimeMS, number, null. The maximum amount of time to allow the query to run.

    • returnOriginal, boolean, true. When false, returns the updated document rather than the original.

    • returnDocsOnly, boolean, true. When true returns only result document.

  • callback, function. The collection result callback.

Returns:

Promise if no callback passed

Examples:
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'findOneAndReplaceExample');

	collection.insertOne({
		a: 1
	}, function(err, insertResult) {
		collection.findOneAndReplace({
			_id: insertResult._id
		}, {
			a: 2
		}, function(err, replaceResult) {
			expect(replaceResult).eql(insertResult);
		});
	});
});
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'findOneAndReplaceExample');

	collection.insertOne({
		a: 1
	}, function(err, insertResult) {
		collection.findOneAndReplace({
			_id: insertResult._id
		}, {
			a: 2
		}, {
			returnDocsOnly: false
		}, function(err, replaceResult) {
			expect(replaceResult).keys(
				'value', 'ok', 'lastErrorObject'
			);
		});
	});
});

findOneAndUpdate(filter, update, options, callback)

Find a document and update it in one atomic operation, requires a write lock for the duration of the operation.

Parameters:

All parameters described as name, type, default value.

  • filter, object. Document selection filter.

  • update, object. Update operations to be performed on the document

  • options, object, null. Optional settings.

    • projection, object, null. Limits the fields to return for all matching documents.

    • sort, object, null. Determines which document the operation modifies if the query selects multiple documents.

    • maxTimeMS, number, null. The maximum amount of time to allow the query to run.

    • returnOriginal, boolean, true. When false, returns the updated document rather than the original.

    • returnDocsOnly, boolean, true. When true returns only result document.

  • callback, function. The collection result callback

Returns:

Promise if no callback passed

Examples:
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'findOneAndUpdateExample');

	collection.insertOne({
		a: 1
	}, function(err, insertResult) {
		collection.findOneAndUpdate({
			_id: insertResult._id
		}, {
			$inc: {a: 1}
		}, function(err, updateResult) {
			expect(updateResult).eql(insertResult);
		});
	});
});
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'findOneAndUpdateExample');

	collection.insertOne({
		a: 1
	}, function(err, insertResult) {
		collection.findOneAndUpdate({
			_id: insertResult._id
		}, {
			$inc: {a: 1}
		}, {
			returnDocsOnly: false
		}, function(err, updateResult) {
			expect(updateResult).keys(
				'value', 'ok', 'lastErrorObject'
			);
		});
	});
});

findOneAndUpsert(filter, update, options, callback)

Upsert a single document on MongoDB.

⚠️ Important. Uses findOneAnReplace and findOneAndUpdate with upsert option under the hood. findOneAndReplace will be used, if update parameter do not contain any update operators (basically, fields begins with $). It can lead to slightly inconsistent behavior, depending on input data. (see db.collection.findOneAndReplace-upsert and db.collection.update upsert behavior to clarify behavior difference). Because of realization it's strongly not recommended using this method on collection with sequenceId and updateDate plugins.

Parameters:
  • filter, object. The Filter used to select the document to upsert

  • update, object. The update operations or replacement document to be applied to the document

  • options, object, null. Optional settings.

    • projection, object, null. Limits the fields to return for all matching documents.

    • sort, object, null. Determines which document the operation modifies if the query selects multiple documents.

    • maxTimeMS, number, null. The maximum amount of time to allow the query to run.

    • returnOriginal, boolean, true. When false, returns the updated document rather than the original.

    • returnDocsOnly, boolean, true. When true returns only result document.

  • callback, function. The command result callback

Returns:

Promise if no callback passed

Examples:
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'findOneAndUpsertExample');

	collection.insertOne({
		a: 1
	}, function(err, insertResult) {
		collection.findOneAndUpsert({
			_id: insertResult._id
		}, {
			$inc: {a: 1}
		}, function(err, upsertResult) {
			expect(upsertResult).eql(insertResult);
		});
	});
});
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'findOneAndUpsertExample');

	collection.insertOne({
		a: 1
	}, function(err, insertResult) {
		collection.findOneAndUpsert({
			_id: insertResult._id
		}, {
			$inc: {a: 1}
		}, {
			returnDocsOnly: false
		}, function(err, upsertResult) {
			expect(upsertResult).keys(
				'value', 'ok', 'lastErrorObject'
			);
		});
	});
});

insertMany(docs, options, 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.

Parameters:

All parameters described as name, type, default value.

  • docs, Array. Documents to insert.

  • options, object, null. Optional settings.

    • w, number | string, null. The write concern.

    • wtimeout, number, null. The write concern timeout.

    • j, boolean, false. Specify a journal write concern.

    • serializeFunctions, boolean, false. Serialize functions on any object.

    • forceServerObjectId, boolean, false. Force server to assign _id values instead of driver.

    • returnDocsOnly, boolean, true. When true returns only result documents.

  • callback, function. The command result callback

Returns:

Promise if no callback passed

Examples:
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'insertManyExample');

	var documents = [{_id: 1, a: 1}, {_id: 2, a: 2}];
	collection.insertMany(documents, function(err, insertResult) {
		expect(insertResult).eql(documents);
	});
});
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'insertManyExample');

	var documents = [{_id: 1, a: 1}, {_id: 2, a: 2}];
	collection.insertMany(documents, {
		returnDocsOnly: false
	}, function(err, insertResult) {
		expect(insertResult).keys(
			'result', 'ops', 'insertedCount', 'insertedIds'
		);
		expect(insertResult.ops).eql(documents);
	});
});

insertOne(doc, options, callback)

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.

Parameters:

All parameters described as name, type, default value.

  • doc, object. Document to insert.

  • options, object, null. Optional settings.

    • w, number | string, null. The write concern.

    • wtimeout, number, null. The write concern timeout.

    • j, boolean, false. Specify a journal write concern.

    • serializeFunctions, boolean, false. Serialize functions on any object.

    • forceServerObjectId, boolean, false. Force server to assign _id values instead of driver.

    • bypassDocumentValidation, boolean, false. Allow driver to bypass schema validation in MongoDB 3.2 or higher.

    • returnDocsOnly, boolean, true. When true returns only result document.

  • callback, function. The command result callback.

Returns:

Promise if no callback passed.

Examples
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'insertOneExample');

	var document = {_id: 1, a: 1};
	collection.insertOne(document, function(err, insertResult) {
		expect(insertResult).eql(document);
	});
});
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'insertOneExample');

	var documents = {_id: 1, a: 1};
	collection.insertOne(documents, {
		returnDocsOnly: false
	}, function(err, insertResult) {
		expect(insertResult).keys(
			'result', 'ops', 'insertedCount', 'insertedId', 'connection'
		);
		expect(insertResult.ops).eql([document]);
	});
});

replaceOne(filter, doc, options, callback)

Replace a document on MongoDB

Parameters:

All parameters described as name, type, default value.

  • filter, object. The Filter used to select the document to update

  • doc, object. The Document that replaces the matching document

  • options, object, null. Optional settings.

    • w, number | string, null. The write concern.

    • wtimeout, number, null. The write concern timeout.

    • j, boolean, false. Specify a journal write concern.

    • bypassDocumentValidation, boolean, false. Allow driver to bypass schema validation in MongoDB 3.2 or higher.

    • returnResultOnly, boolean, true. Specifying result returning in callback.

  • callback, function. The command result callback.

Returns:

Promise if no callback passed.

Examples:
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'replaceOneExample');

	collection.insertOne({
		a: 1
	}, function(err, insertResult) {
		collection.replaceOne({
			_id: insertResult._id
		}, {
			a: 2
		}, function(err, replaceResult) {
			expect(replaceResult).keys(
				'matchedCount', 'modifiedCount', 'upsertedId'
			);
		});
	});
});
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'replaceOneExample');

	collection.insertOne({
		a: 1
	}, function(err, insertResult) {
		collection.replaceOne({
			_id: insertResult._id
		}, {
			a: 2
		}, {
			returnDocsOnly: false
		}, function(err, replaceResult) {
			expect(replaceResult).keys(
				'result', 'connection', 'matchedCount', 'modifiedCount',
				'upsertedId', 'upsertedCount', 'ops'
			);
		});
	});
});

updateMany(filter, update, options, callback)

Update multiple documents on MongoDB

Parameters:

All parameters described as name, type, default value.

  • filter, object. The Filter used to select the document to update

  • update, object. The update operations to be applied to the document

  • options, object, null. Optional settings.

    • w, number | string, null. The write concern.

    • wtimeout, number, null. The write concern timeout.

    • j, boolean, false. Specify a journal write concern.

    • returnResultOnly, boolean, true. Specifying result returning in callback.

  • callback, function. The command result callback

Returns:

Promise if no callback passed.

Examples:
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'updateManyExample');

	var documents = [{_id: 1, a: 1}, {_id: 2, a: 1}];
	collection.insertMany(documents, function(err, insertResult) {
		collection.updateMany({
			a: 1
		}, {
			a: {$inc: 1}
		}, function(err, updateResult) {
			expect(updateResult).keys(
				'matchedCount', 'modifiedCount', 'upsertedId'
			);
		});
	});
});
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'updateManyExample');

	var documents = [{_id: 1, a: 1}, {_id: 2, a: 1}];
	collection.insertMany(documents, function(err, insertResult) {
		collection.updateMany({
			a: 1
		}, {
			a: {$inc: 1}
		}, {
			returnResultOnly: false
		}, function(err, updateResult) {
			expect(updateResult).keys(
				'connection', 'result', 'matchedCount', 'modifiedCount',
				'upsertedId', 'upsertedCount'
			);
		});
	});
});

updateOne(filter, update, options, callback)

Update a single document on MongoDB

Parameters:
  • filter, object. The Filter used to select the document to update

  • update, object. The update operations to be applied to the document

  • options, object, null. Optional settings.

    • w, number | string, null. The write concern.

    • wtimeout, number, null, The write concern timeout.

    • j, boolean, false. Specify a journal write concern.

    • bypassDocumentValidation, boolean, false. Allow driver to bypass schema validation in MongoDB 3.2 or higher.

    • returnResultOnly, boolean, true. Specifying result returning in callback.

  • callback, function. The command result callback

Returns:

Promise if no callback passed.

Examples:
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'updateOneExample');

	var document = {_id: 1, a: 1};
	collection.insertOne(document, function(err, insertResult) {
		collection.updateOne({
			a: 1
		}, {
			a: {$inc: 1}
		}, function(err, updateResult) {
			expect(updateResult).keys(
				'matchedCount', 'modifiedCount', 'upsertedId'
			);
		});
	});
});
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection,
	expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'updateOneExample');

	var document = {_id: 1, a: 1};
	collection.insertOne(document, function(err, insertResult) {
		collection.updateOne({
			a: 1
		}, {
			a: {$inc: 1}
		}, {
			returnResultOnly: false
		}, function(err, updateResult) {
			expect(updateResult).keys(
				'connection', 'result', 'matchedCount', 'modifiedCount',
				'upsertedId', 'upsertedCount'
			);
		});
	});
});

count(query, options, callback)

Returns the count of documents that would match a query.

Parameters:
  • query, object. The Filter used to select the document to upsert. Optional.

  • options, object, null. Optional settings.

    • limit, integer. The maximum number of documents to count.

    • skip, integer. The number of documents to skip before counting.

    • hint, string or object. An index name hint or specification for the query.

    • maxTimeMS, integer. The maximum amount of time to allow the query to run.

    • readConcern, string, default to local. Specifies the read concern.

  • callback, function. The command result callback

Returns:

Promise if no callback passed

Examples:
var MongoClient = require('mongodb').MongoClient;
var Collection = require('mongodbext').Collection;
var expect = require('expect.js');

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'countExample');

	collection.insertMany([{
		a: 1
	}, {
		a: 2
	}], function() {
		collection.count({
			a: 1
		}, function(err, countResult) {
			expect(countResult).equal(1);
		});
	});
});

Hooks

All hooks take two parameters: params and callback. Callback is always callback function, and params fields depends on hook.

Name | Methods | Params fields ---- | ------- | ------------- beforeInsertOne | insertOne | obj, document to insertoptions, optional settings afterInsertOne | insertOne | obj, inserted documentoptions, optional settings beforeInsertMany | insertMany | objs, documents to insertoptions, optional settings afterInsertMany | insertMany | objs, inserted documentsoptions, optional settings beforeUpdateOne | updateOnefindOneAndUpdate | condition, query to select documentsmodifier, update operationsoptions, optional settings afterUpdateOne | updateOnefindOneAndUpdate | condition, query to select documentsmodifier, update operationsoptions, optional settingsresult, operation result beforeUpdateMany | updateMany | condition, query to select documentsmodifier, update operationsoptions, optional settings afterUpdateMany | updateMany | condition, query to select documentsmodifier, update operationsoptions, optional settingsresult, operation result beforeDeleteOne | deleteOnefindOneAndDelete | condition, query to select documentsoptions, optional settings afterDeleteOne | deleteOnefindOneAndDelete | condition, query to select documentsoptions, optional settingsresult, operation result beforeDeleteMany | deleteMany | condition, query to select documentsoptions, optional settings afterDeleteMany | deleteMany | condition, query to select documentsoptions, optional settingsresult, operation result beforeReplaceOne | replaceOnefindOneAndReplace | condition, query to select documentsreplacement, document to replace originaloptions, optional settings afterReplaceOne | replaceOnefindOneAndReplace | condition, query to select documentsreplacement, document to replace originaloptions, optional settingsresult, operation result beforeUpsertOne | findOneAndUpsert | condition, query to select documentsmodifier, update operationsoptions, optional settings afterUpsertOne | findOneAndUpsert | condition, query to select documentsmodifier, update operationsoptions, optional settingsobj, upserted documentisUpdated, flag indicating whether document was updated or inserted

Plugins

Collection class allows to create and use plugins for adding auto-generated fields to documents, for example.

addPlugin(plugin, options)

Add plugin to collection.

Parameters:
  • plugin, function | string. It can be either plugin function, or in case of built-in plugins it's name. Plugin function takes collection object as first parameter and optional options as second

  • options, object, null. Options that will be passed to plugin.

Examples:
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection;

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'updateOneExample');

	collection.addPlugin(function(collection) {
		collection.on('insertOne', function(params, callback) {
			params.obj.counter = 1;
			callback();
		});
	});
});
var MongoClient = require('mongodb').MongoClient,
	Collection = require('mongodbext').Collection;

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
	var collection = new Collection(db, 'updateOneExample');

	collection.addPlugin('sequenceId');
	collection.addPlugin('unsupportedMethods', {
		methods: ['insertMany', 'updateMany']
	});
});

Built-in plugins

sequenceId

Replace mongo-style object _id with number.

⚠️ Do not work with findOneAndUpsert().

options:

  • seqCollectionName - name of sequences collection ('__sequences' by default)
  • seqName - name of sequence (collection name by default)
  • key - key in document to set sequence value (_id by default)
createDate

Add createDate to each inserted to collection document

options:

  • format - date format that will be used as createDate, available values:
    • 'timestamp' (default) - integer timestamp date in milliseconds (.getTime())
    • 'string' - string date (.toString())
    • 'ISOString' - string date in ISO format (.toISOString())
    • 'ISODate' - date as Date object (new Date())
    • function(date) - custom user function that should return formatted date
updateDate

Add updateDate to each updated or replaces document

⚠️ Do not work properly with findOneAndUpsert(), createDate will be rewrote every time.

options:

  • format - date format that will be used as updateDate, available values:
    • 'timestamp' (default) - integer timestamp date in milliseconds (.getTime())
    • 'string' - string date (.toString())
    • 'ISOString' - string date in ISO format (.toISOString())
    • 'ISODate' - date as Date object (new Date())
    • function(date) - custom user function that should return formatted date
detailedError

Add field operation with query info to error object