# DWHQL

DWQHL - это язык (полностью совместимый с ES6), предназначенный для запросов и обработки данных.

# Выполнение запросов локально

DWHQL Simulator

# Требования

  • MongoDB
  • Node.js >=10.x
  • Yarn || NPM

# Демо

demo

# Глобальые функции и переменные

  • resolve(...args) - передает выходные данные
  • reject(...args) - передает ошибку.
  • db - см. ниже.

# db

# Example:

// Create Document
new db({ name: "Foo" })
  .save()
  .then(resolve)
  .catch(reject);

// Find Document
db.findOne({ name: "Foo" })
  .exec()
  .then(resolve)
  .catch(reject);

# db.count()

# Parameters
  • filter «Object»
  • [callback] «Function»
# Returns:
  • «Query»

Counts number of documents that match filter in a database collection.

This method is deprecated. If you want to count the number of documents in a collection, e.g. count({}), use the estimatedDocumentCount() function instead. Otherwise, use the countDocuments() function instead.

# Example:

db.count({ type: 'jungle' }, function (err, count) {
  if (err) ..
  console.log('there are %d jungle adventures', count);
});

# db.countDocuments()

# Parameters
  • filter «Object»
  • [callback] «Function»
# Returns:
  • «Query»

Counts number of documents matching filter in a database collection.

# Example:

db.countDocuments({ type: 'jungle' }, function (err, count) {
  console.log('there are %d jungle adventures', count);
});

If you want to count all documents in a large collection, use the estimatedDocumentCount() function instead. If you call countDocuments({}), MongoDB will always execute a full collection scan and not use any indexes.

The countDocuments() function is similar to count(), but there are a few operators that countDocuments() does not support. Below are the operators that count() supports but countDocuments() does not, and the suggested replacement:


# db.create()

# Parameters
  • docs «Array|Object» Documents to insert, as a spread or array
  • [options] «Object» Options passed down to save(). To specify options, docs must be an array, not a spread.
  • [callback] «Function» callback
# Returns:
  • «Promise»

Shortcut for saving one or more documents to the database. Mydb.create(docs) does new Mydb(doc).save() for every doc in docs.

This function triggers the following middleware.

  • save()

# Example:

// pass a spread of docs and a callback
db.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) {
  if (err) // ...
});

// pass an array of docs
var array = [{ type: 'jelly bean' }, { type: 'snickers' }];
db.create(array, function (err, candies) {
  if (err) // ...

  var jellybean = candies[0];
  var snickers = candies[1];
  // ...
});

// callback is optional; use the returned promise if you like:
var promise = db.create({ type: 'jawbreaker' });
promise.then(function (jawbreaker) {
  // ...
})

# db.deleteOne()

# Parameters
# Returns:
  • «Query»

Deletes the first document that matches conditions from the collection. Behaves like remove(), but deletes at most one document regardless of the single option.

# Example:

Character.deleteOne({ name: 'Eddard Stark' }, function (err) {});

# Note:

Like db.remove(), this function does not trigger pre('remove') or post('remove') hooks.


# db.distinct()

# Parameters
  • field «String»
  • [conditions] «Object» optional
  • [callback] «Function»
# Returns:
  • «Query»

Creates a Query for a distinct operation.

Passing a callback executes the query.

# Example

Link.distinct('url', { clicks: {$gt: 100}}, function (err, result) {
  if (err) return handleError(err);

  assert(Array.isArray(result));
  console.log('unique urls with more than 100 clicks', result);
})

var query = Link.distinct('url');
query.exec(callback);

# db.estimatedDocumentCount()

# Parameters
  • [options] «Object»
  • [callback] «Function»
# Returns:
  • «Query»

Estimates the number of documents in the MongoDB collection. Faster than using countDocuments() for large collections because estimatedDocumentCount() uses collection metadata rather than scanning the entire collection.

# Example:

const numdbs = db.estimatedDocumentCount();

# db.events

# Type:
  • «property»

Event emitter that reports any errors that occurred. Useful for global error handling.

# Example:

Mydb.events.on('error', err => console.log(err.message));

// Prints a 'CastError' because of the above handler
await Mydb.findOne({ _id: 'notanid' }).catch(noop);

# db.exists()

# Parameters
  • filter «Object»
  • [callback] «Function» callback
# Returns:
  • «Promise»

Returns true if at least one document exists in the database that matches the given filter, and false otherwise.

Under the hood, Mydb.exists({ answer: 42 }) is equivalent to Mydb.findOne({ answer: 42 }).select({ _id: 1 }).lean().then(doc => !!doc)

# Example:

await Character.deleteMany({});
await Character.create({ name: 'Jean-Luc Picard' });

await Character.exists({ name: /picard/i }); // true
await Character.exists({ name: /riker/i }); // false

This function triggers the following middleware.

  • findOne()

# db.find()

# Parameters
# Returns:
  • «Query»

Finds documents

The conditions are cast to their respective SchemaTypes before the command is sent.

# Examples:

// named john and at least 18
Mydb.find({ name: 'john', age: { $gte: 18 }});

// executes, passing results to callback
Mydb.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});

// executes, name LIKE john and only selecting the "name" and "friends" fields
Mydb.find({ name: /john/i }, 'name friends', function (err, docs) { })

// passing options
Mydb.find({ name: /john/i }, null, { skip: 10 })

// passing options and executes
Mydb.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});

// executing a query explicitly
var query = Mydb.find({ name: /john/i }, null, { skip: 10 })
query.exec(function (err, docs) {});

// using the promise returned from executing a query
var query = Mydb.find({ name: /john/i }, null, { skip: 10 });
var promise = query.exec();
promise.addBack(function (err, docs) {});

# db.findById()

# Parameters
# Returns:
  • «Query»

Finds a single document by its _id field. findById(id) is almost* equivalent to findOne({ _id: id }). If you want to query by a document's _id, use findById() instead of findOne().

The id is cast based on the Schema before sending the command.

This function triggers the following middleware.

  • findOne()

* Except for how it treats undefined. If you use findOne(), you'll see that findOne(undefined) and findOne({ _id: undefined }) are equivalent to findOne({}) and return arbitrary documents. However, mongoose translates findById(undefined) into findOne({ _id: null }).

# Example:

// find adventure by id and execute
db.findById(id, function (err, adventure) {});

// same as above
db.findById(id).exec(callback);

// select only the adventures name and length
db.findById(id, 'name length', function (err, adventure) {});

// same as above
db.findById(id, 'name length').exec(callback);

// include all properties except for `length`
db.findById(id, '-length').exec(function (err, adventure) {});

// passing options (in this case return the raw js objects, not mongoose documents by passing `lean`
db.findById(id, 'name', { lean: true }, function (err, doc) {});

// same as above
db.findById(id, 'name').lean().exec(function (err, doc) {});

# db.findByIdAndDelete()

# Parameters
# Returns:
  • «Query»

Issue a MongoDB findOneAndDelete() command by a document's _id field. In other words, findByIdAndDelete(id) is a shorthand for findOneAndDelete({ _id: id }).

This function triggers the following middleware.

  • findOneAndDelete()

# db.findByIdAndRemove()

# Parameters
# Returns:
  • «Query»

Issue a mongodb findAndModify remove command by a document's _id field. findByIdAndRemove(id, ...) is equivalent to findOneAndRemove({ _id: id }, ...).

Finds a matching document, removes it, passing the found document (if any) to the callback.

Executes the query if callback is passed.

This function triggers the following middleware.

  • findOneAndRemove()

# Options:

  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • select: sets the document fields to return
  • rawResult: if true, returns the raw result from the MongoDB driver
  • strict: overwrites the schema's strict mode option for this update

# Examples:

A.findByIdAndRemove(id, options, callback) // executes
A.findByIdAndRemove(id, options)  // return Query
A.findByIdAndRemove(id, callback) // executes
A.findByIdAndRemove(id) // returns Query
A.findByIdAndRemove()           // returns Query

# db.findByIdAndUpdate()

# Parameters
  • id «Object|Number|String» value of _id to query by

  • [update] «Object»

  • [options] «Object» optional see Query.prototype.setOptions()

  • [options.lean] «Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See Query.lean() and the Mongoose lean tutorial.

  • [options.strict] «Boolean|String» overwrites the schema's strict mode option

  • [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is undefined when casting an update. In other words, if this is set, Mongoose will delete baz from the update in db.updateOne({}, { foo: 'bar', baz: undefined }) before sending the update to the server.

  • [callback] «Function»

# Returns:
  • «Query»

Issues a mongodb findAndModify update command by a document's _id field. findByIdAndUpdate(id, ...) is equivalent to findOneAndUpdate({ _id: id }, ...).

Finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback. The query executes if callback is passed.

This function triggers the following middleware.

  • findOneAndUpdate()

# Options:

  • new: bool - true to return the modified document rather than the original. defaults to false
  • upsert: bool - creates the object if it doesn't exist. defaults to false.
  • runValidators: if true, runs update validators on this command. Update validators validate the update operation against the model's schema.
  • setDefaultsOnInsert: if this and upsert are true, mongoose will apply the defaults specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on MongoDB's $setOnInsert operator.
  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • select: sets the document fields to return
  • rawResult: if true, returns the raw result from the MongoDB driver
  • strict: overwrites the schema's strict mode option for this update

# Examples:

A.findByIdAndUpdate(id, update, options, callback) // executes
A.findByIdAndUpdate(id, update, options)  // returns Query
A.findByIdAndUpdate(id, update, callback) // executes
A.findByIdAndUpdate(id, update)           // returns Query
A.findByIdAndUpdate()                     // returns Query

# Note:

All top level update keys which are not atomic operation names are treated as set operations:

# Example:

db.findByIdAndUpdate(id, { name: 'jason bourne' }, options, callback)

// is sent as
db.findByIdAndUpdate(id, { $set: { name: 'jason bourne' }}, options, callback)

This helps prevent accidentally overwriting your document with { name: 'jason bourne' }.

# Note:

Values are cast to their appropriate types when using the findAndModify helpers. However, the below are not executed by default.

  • defaults. Use the setDefaultsOnInsert option to override.

findAndModify helpers support limited validation. You can enable these by setting the runValidators options, respectively.

If you need full-fledged validation, use the traditional approach of first retrieving the document.

db.findById(id, function (err, doc) {
  if (err) ..
  doc.name = 'jason bourne';
  doc.save(callback);
});

# db.findOne()

# Parameters
# Returns:
  • «Query»

Finds one document.

The conditions are cast to their respective SchemaTypes before the command is sent.

Note: conditions is optional, and if conditions is null or undefined, mongoose will send an empty findOne command to MongoDB, which will return an arbitrary document. If you're querying by _id, use findById() instead.

# Example:

// find one iphone adventures - iphone adventures??
db.findOne({ type: 'iphone' }, function (err, adventure) {});

// same as above
db.findOne({ type: 'iphone' }).exec(function (err, adventure) {});

// select only the adventures name
db.findOne({ type: 'iphone' }, 'name', function (err, adventure) {});

// same as above
db.findOne({ type: 'iphone' }, 'name').exec(function (err, adventure) {});

// specify options, in this case lean
db.findOne({ type: 'iphone' }, 'name', { lean: true }, callback);

// same as above
db.findOne({ type: 'iphone' }, 'name', { lean: true }).exec(callback);

// chaining findOne queries (same as above)
db.findOne({ type: 'iphone' }).select('name').lean().exec(callback);

# db.findOneAndDelete()

# Parameters
# Returns:
  • «Query»

Issue a MongoDB findOneAndDelete() command.

Finds a matching document, removes it, and passes the found document (if any) to the callback.

Executes the query if callback is passed.

This function triggers the following middleware.

  • findOneAndDelete()

This function differs slightly from db.findOneAndRemove() in that findOneAndRemove() becomes a MongoDB findAndModify() command, as opposed to a findOneAndDelete() command. For most mongoose use cases, this distinction is purely pedantic. You should use findOneAndDelete() unless you have a good reason not to.

# Options:

  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
  • select: sets the document fields to return
  • projection: like select, it determines which fields to return, ex. { projection: { _id: 0 } }
  • rawResult: if true, returns the raw result from the MongoDB driver
  • strict: overwrites the schema's strict mode option for this update

# Examples:

A.findOneAndDelete(conditions, options, callback) // executes
A.findOneAndDelete(conditions, options)  // return Query
A.findOneAndDelete(conditions, callback) // executes
A.findOneAndDelete(conditions) // returns Query
A.findOneAndDelete()           // returns Query

Values are cast to their appropriate types when using the findAndModify helpers. However, the below are not executed by default.

  • defaults. Use the setDefaultsOnInsert option to override.

findAndModify helpers support limited validation. You can enable these by setting the runValidators options, respectively.

If you need full-fledged validation, use the traditional approach of first retrieving the document.

db.findById(id, function (err, doc) {
  if (err) ..
  doc.name = 'jason bourne';
  doc.save(callback);
});

# db.findOneAndRemove()

# Parameters
# Returns:
  • «Query»

Issue a mongodb findAndModify remove command.

Finds a matching document, removes it, passing the found document (if any) to the callback.

Executes the query if callback is passed.

This function triggers the following middleware.

  • findOneAndRemove()

# Options:

  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
  • select: sets the document fields to return
  • projection: like select, it determines which fields to return, ex. { projection: { _id: 0 } }
  • rawResult: if true, returns the raw result from the MongoDB driver
  • strict: overwrites the schema's strict mode option for this update

# Examples:

A.findOneAndRemove(conditions, options, callback) // executes
A.findOneAndRemove(conditions, options)  // return Query
A.findOneAndRemove(conditions, callback) // executes
A.findOneAndRemove(conditions) // returns Query
A.findOneAndRemove()           // returns Query

Values are cast to their appropriate types when using the findAndModify helpers. However, the below are not executed by default.

  • defaults. Use the setDefaultsOnInsert option to override.

findAndModify helpers support limited validation. You can enable these by setting the runValidators options, respectively.

If you need full-fledged validation, use the traditional approach of first retrieving the document.

db.findById(id, function (err, doc) {
  if (err) ..
  doc.name = 'jason bourne';
  doc.save(callback);
});

# db.findOneAndReplace()

# Parameters
  • filter «Object» Replace the first document that matches this filter

  • [replacement] «Object» Replace with this document

  • [options] «Object» optional see Query.prototype.setOptions()

  • [options.lean] «Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See Query.lean().

  • [options.strict] «Boolean|String» overwrites the schema's strict mode option

  • [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is undefined when casting an update. In other words, if this is set, Mongoose will delete baz from the update in db.updateOne({}, { foo: 'bar', baz: undefined }) before sending the update to the server.

  • [callback] «Function»

# Returns:
  • «Query»

Issue a MongoDB findOneAndReplace() command.

Finds a matching document, replaces it with the provided doc, and passes the returned doc to the callback.

Executes the query if callback is passed.

This function triggers the following query middleware.

  • findOneAndReplace()

# Options:

  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
  • select: sets the document fields to return
  • projection: like select, it determines which fields to return, ex. { projection: { _id: 0 } }
  • rawResult: if true, returns the raw result from the MongoDB driver
  • strict: overwrites the schema's strict mode option for this update

# Examples:

A.findOneAndReplace(conditions, options, callback) // executes
A.findOneAndReplace(conditions, options)  // return Query
A.findOneAndReplace(conditions, callback) // executes
A.findOneAndReplace(conditions) // returns Query
A.findOneAndReplace()           // returns Query

Values are cast to their appropriate types when using the findAndModify helpers. However, the below are not executed by default.

  • defaults. Use the setDefaultsOnInsert option to override.

# db.findOneAndUpdate()

# Parameters
  • [conditions] «Object»

  • [update] «Object»

  • [options] «Object» optional see Query.prototype.setOptions()

  • [options.lean] «Object» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See Query.lean() and the Mongoose lean tutorial.

  • [options.strict] «Boolean|String» overwrites the schema's strict mode option

  • [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is undefined when casting an update. In other words, if this is set, Mongoose will delete baz from the update in db.updateOne({}, { foo: 'bar', baz: undefined }) before sending the update to the server.

  • [callback] «Function»

# Returns:
  • «Query»

Issues a mongodb findAndModify update command.

Finds a matching document, updates it according to the update arg, passing any options, and returns the found document (if any) to the callback. The query executes if callback is passed else a Query object is returned.

# Options:

  • new: bool - if true, return the modified document rather than the original. defaults to false (changed in 4.0)
  • upsert: bool - creates the object if it doesn't exist. defaults to false.
  • fields: {Object|String} - Field selection. Equivalent to .select(fields).findOneAndUpdate()
  • maxTimeMS: puts a time limit on the query - requires mongodb >= 2.6.0
  • sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
  • runValidators: if true, runs update validators on this command. Update validators validate the update operation against the model's schema.
  • setDefaultsOnInsert: if this and upsert are true, mongoose will apply the defaults specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on MongoDB's $setOnInsert operator.
  • rawResult: if true, returns the raw result from the MongoDB driver
  • strict: overwrites the schema's strict mode option for this update

# Examples:

A.findOneAndUpdate(conditions, update, options, callback) // executes
A.findOneAndUpdate(conditions, update, options)  // returns Query
A.findOneAndUpdate(conditions, update, callback) // executes
A.findOneAndUpdate(conditions, update)           // returns Query
A.findOneAndUpdate()                             // returns Query

# Note:

All top level update keys which are not atomic operation names are treated as set operations:

# Example:

var query = { name: 'borne' };
db.findOneAndUpdate(query, { name: 'jason bourne' }, options, callback)

// is sent as
db.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options, callback)

This helps prevent accidentally overwriting your document with { name: 'jason bourne' }.

# Note:

Values are cast to their appropriate types when using the findAndModify helpers. However, the below are not executed by default.

  • defaults. Use the setDefaultsOnInsert option to override.

findAndModify helpers support limited validation. You can enable these by setting the runValidators options, respectively.

If you need full-fledged validation, use the traditional approach of first retrieving the document.

db.findById(id, function (err, doc) {
  if (err) ..
  doc.name = 'jason bourne';
  doc.save(callback);
});

# db.geoSearch()

# Parameters
  • conditions «Object» an object that specifies the match condition (required)

  • options «Object» for the geoSearch, some (near, maxDistance) are required

  • [options.lean] «Object|Boolean» if truthy, mongoose will return the document as a plain JavaScript object rather than a mongoose document. See Query.lean() and the Mongoose lean tutorial.

  • [callback] «Function» optional callback

# Returns:
  • «Promise»

Implements $geoSearch functionality for Mongoose

This function does not trigger any middleware

# Example:

var options = { near: [10, 10], maxDistance: 5 };
Locations.geoSearch({ type : "house" }, options, function(err, res) {
  console.log(res);
});

# Options:

  • near {Array} x,y point to search for
  • maxDistance {Number} the maximum distance from the point near that a result can be
  • limit {Number} The maximum number of results to return
  • lean {Object|Boolean} return the raw object instead of the Mongoose db

# db.hydrate()

# Parameters
  • obj «Object»
# Returns:
  • «db» document instance

Shortcut for creating a new Document from existing raw data, pre-saved in the DB. The document returned has no paths marked as modified initially.

# Example:

// hydrate previous data into a Mongoose document
var mongoosedb = db.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' });

# db.init()

# Parameters
  • [callback] «Function»

This function is responsible for building indexes, unless autoIndex is turned off.

Mongoose calls this function automatically when a model is created using mongoose.model() or * connection.model(), so you don't need to call it. This function is also idempotent, so you may call it to get back a promise that will resolve when your indexes are finished building as an alternative to Mydb.on('index')

# Example:

var eventSchema = new Schema({ thing: { type: 'string', unique: true }})
// This calls `Event.init()` implicitly, so you don't need to call
// `Event.init()` on your own.
var Event = mongoose.model('Event', eventSchema);

Event.init().then(function(Event) {
  // You can also use `Event.on('index')` if you prefer event emitters
  // over promises.
  console.log('Indexes are done building!');
});

# db.insertMany()

# Parameters
  • doc(s) «Array|Object|*»
  • [options] «Object» see the mongodb driver options
  • [options.ordered «Boolean» = true] if true, will fail fast on the first error encountered. If false, will insert all the documents it can and report errors later. An insertMany() with ordered = false is called an "unordered" insertMany().
  • [options.rawResult «Boolean» = false] if false, the returned promise resolves to the documents that passed mongoose document validation. If true, will return the raw result from the MongoDB driver with a mongoose property that contains validationErrors if this is an unordered insertMany.
  • [callback] «Function» callback
# Returns:
  • «Promise»

Shortcut for validating an array of documents and inserting them into MongoDB if they're all valid. This function is faster than .create() because it only sends one operation to the server, rather than one for each document.

Mongoose always validates each document before sending insertMany to MongoDB. So if one document has a validation error, no documents will be saved, unless you set the ordered option to false.

This function does not trigger save middleware.

This function triggers the following middleware.

  • insertMany()

# Example:

var arr = [{ name: 'Star Wars' }, { name: 'The Empire Strikes Back' }];
Movies.insertMany(arr, function(error, docs) {});

# db.listIndexes()

# Parameters
  • [cb] «Function» optional callback
# Returns:
  • «Promise,undefined» Returns undefined if callback is specified, returns a promise if no callback.

Lists the indexes currently defined in MongoDB. This may or may not be the same as the indexes defined in your schema depending on whether you use the autoIndex option and if you build indexes manually.


# db.mapReduce()

# Parameters
  • o «Object» an object specifying map-reduce options
  • [callback] «Function» optional callback
# Returns:
  • «Promise»

Executes a mapReduce command.

o is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation. See node-mongodb-native mapReduce() documentation for more detail about options.

This function does not trigger any middleware.

# Example:

var o = {};
// `map()` and `reduce()` are run on the MongoDB server, not Node.js,
// these functions are converted to strings
o.map = function () { emit(this.name, 1) };
o.reduce = function (k, vals) { return vals.length };
db.mapReduce(o, function (err, results) {
  console.log(results)
})

# Other options:

  • query {Object} query filter object.
  • sort {Object} sort input objects using this key
  • limit {Number} max number of documents
  • keeptemp {Boolean, default:false} keep temporary data
  • finalize {Function} finalize function
  • scope {Object} scope variables exposed to map/reduce/finalize during execution
  • jsMode {Boolean, default:false} it is possible to make the execution stay in JS. Provided in MongoDB > 2.0.X
  • verbose {Boolean, default:false} provide statistics on job execution time.
  • readPreference {String}
  • out* {Object, default: {inline:1}} sets the output target for the map reduce job.

# * out options:

  • {inline:1} the results are returned in an array
  • {replace: 'collectionName'} add the results to collectionName: the results replace the collection
  • {reduce: 'collectionName'} add the results to collectionName: if dups are detected, uses the reducer / finalize functions
  • {merge: 'collectionName'} add the results to collectionName: if dups exist the new docs overwrite the old

If options.out is set to replace, merge, or reduce, a db instance is returned that can be used for further querying. Queries run against this model are all executed with the lean option; meaning only the js object is returned and no Mongoose magic is applied (getters, setters, etc).

# Example:

var o = {};
// You can also define `map()` and `reduce()` as strings if your
// linter complains about `emit()` not being defined
o.map = 'function () { emit(this.name, 1) }';
o.reduce = 'function (k, vals) { return vals.length }';
o.out = { replace: 'createdCollectionNameForResults' }
o.verbose = true;

db.mapReduce(o, function (err, model, stats) {
  console.log('map reduce took %d ms', stats.processtime)
  model.find().where('value').gt(10).exec(function (err, docs) {
    console.log(docs);
  });
})

// `mapReduce()` returns a promise. However, ES6 promises can only
// resolve to exactly one value,
o.resolveToObject = true;
var promise = db.mapReduce(o);
promise.then(function (res) {
  var model = res.model;
  var stats = res.stats;
  console.log('map reduce took %d ms', stats.processtime)
  return model.find().where('value').gt(10).exec();
}).then(function (docs) {
   console.log(docs);
}).then(null, handleError).end()

# db.populate()

# Parameters
  • docs «Document|Array» Either a single document or array of documents to populate.

  • options «Object» A hash of key/val (path, options) used for population.

  • [options.retainNullValues=false] «boolean» by default, Mongoose removes null and undefined values from populated arrays. Use this option to make populate() retain null and undefined array entries.

  • [options.getters=false] «boolean» if true, Mongoose will call any getters defined on the localField. By default, Mongoose gets the raw value of localField. For example, you would need to set this option to true if you wanted to add a lowercase getter to your localField.

  • [options.clone=false] «boolean» When you do BlogPost.find().populate('author'), blog posts with the same author will share 1 copy of an author doc. Enable this option to make Mongoose clone populated docs before assigning them.

  • [options.match=null] «Object|Function» Add an additional filter to the populate query. Can be a filter object containing MongoDB query syntax, or a function that returns a filter object.

  • [options.skipInvalidIds=false] «Boolean» By default, Mongoose throws a cast error if localField and foreignField schemas don't line up. If you enable this option, Mongoose will instead filter out any localField properties that cannot be casted to foreignField's schema type.

  • [callback(err,doc)] «Function» Optional callback, executed upon completion. Receives err and the doc(s).

# Returns:
  • «Promise»

Populates document references.

# Available top-level options:

  • path: space delimited path(s) to populate
  • select: optional fields to select
  • match: optional query conditions to match
  • model: optional name of the model to use for population
  • options: optional query options like sort, limit, etc
  • justOne: optional boolean, if true Mongoose will always set path to an array. Inferred from schema by default.

# Examples:

// populates a single object
db.findById(id, function (err, user) {
  var opts = [
    { path: 'company', match: { x: 1 }, select: 'name' },
    { path: 'notes', options: { limit: 10 }, model: 'override' }
  ];

  db.populate(user, opts, function (err, user) {
    console.log(user);
  });
});

// populates an array of objects
db.find(match, function (err, users) {
  var opts = [{ path: 'company', match: { x: 1 }, select: 'name' }];

  var promise = db.populate(users, opts);
  promise.then(console.log).end();
})

// imagine a db model exists with two saved documents:
//   { _id: 389, name: 'whip' }
//   { _id: 8921, name: 'boomerang' }
// and this schema:
// new Schema({
//   name: String,
//   weapon: { type: ObjectId, ref: 'db' }
// });

var user = { name: 'Indiana Jones', weapon: 389 };
db.populate(user, { path: 'weapon', model: 'db' }, function (err, user) {
  console.log(user.weapon.name); // whip
})

// populate many plain objects
var users = [{ name: 'Indiana Jones', weapon: 389 }]
users.push({ name: 'Batman', weapon: 8921 })
db.populate(users, { path: 'weapon' }, function (err, users) {
  users.forEach(function (user) {
    console.log('%s uses a %s', users.name, user.weapon.name)
    // Indiana Jones uses a whip
    // Batman uses a boomerang
  });
});
// Note that we didn't need to specify the db model because
// it is in the schema's ref

# db.prototype.$where

# Type:
  • «property»

Additional properties to attach to the query when calling save() and isNew is false.


# db.prototype.$where()

# Parameters
  • argument «String|Function» is a javascript string or anonymous function
# Returns:
  • «Query»

Creates a Query and specifies a $where condition.

Sometimes you need to query for things in mongodb using a JavaScript expression. You can do so via find({ $where: javascript }), or you can use the mongoose shortcut method $where via a Query chain or from your mongoose db.

Blog.$where('this.username.indexOf("val") !== -1').exec(function (err, docs) {});

# db.prototype.base

# Type:
  • «property»

Base Mongoose instance the model uses.


# db.prototype.basedbName

# Type:
  • «property»

If this is a discriminator model, basedbName is the name of the base model.


# db.prototype.collection

# Type:
  • «property»

Collection the model uses.

This property is read-only. Modifying this property is a no-op.


# db.prototype.db

# Type:
  • «property»

Connection the model uses.


# db.prototype.delete

# Type:
  • «property»

Alias for remove


# db.prototype.deleteOne()

# Parameters
  • [fn] «function(err|product)» optional callback
# Returns:
  • «Promise» Promise

Removes this document from the db. Equivalent to .remove().

# Example:

product = await product.deleteOne();
await Product.findById(product._id); // null

# db.prototype.discriminators

# Type:
  • «property»

Registered discriminators for this model.


# db.prototype.increment()

Signal that we desire an increment of this documents version.

# Example:

db.findById(id, function (err, doc) {
  doc.increment();
  doc.save(function (err) { .. })
})

# db.prototype.model()

# Parameters
  • name «String» model name

Returns another db instance.

# Example:

var doc = new Tank;
doc.model('db').findById(id, callback);

# db.prototype.modelName

# Type:
  • «property»

The name of the model


# db.prototype.remove()

# Parameters
  • [fn] «function(err|product)» optional callback
# Returns:
  • «Promise» Promise

Removes this document from the db.

# Example:

product.remove(function (err, product) {
  if (err) return handleError(err);
  Product.findById(product._id, function (err, product) {
    console.log(product) // null
  })
})

As an extra measure of flow control, remove will return a Promise (bound to fn if passed) so it could be chained, or hooked to recieve errors

# Example:

product.remove().then(function (product) {
   ...
}).catch(function (err) {
   assert.ok(err)
})

# db.prototype.save()

# Parameters
# Returns:
  • «Promise,undefined» Returns undefined if used with callback or a Promise otherwise.

Saves this document.

# Example:

product.sold = Date.now();
product = await product.save();

If save is successful, the returned promise will fulfill with the document saved.

# Example:

const newProduct = await product.save();
newProduct === product; // true

# db.prototype.schema

# Type:
  • «property»

Schema the model uses.


# db.remove()

# Parameters
  • conditions «Object»
  • [callback] «Function»
# Returns:
  • «Query»

Removes all documents that match conditions from the collection. To remove just the first document that matches conditions, set the single option to true.

# Example:

const res = await Character.remove({ name: 'Eddard Stark' });
res.deletedCount; // Number of documents removed

# Note:

This method sends a remove command directly to MongoDB, no Mongoose documents are involved. Because no Mongoose documents are involved, Mongoose does not execute document middleware.


# db.replaceOne()

# Parameters
  • filter «Object»

  • doc «Object»

  • [options] «Object» optional see Query.prototype.setOptions()

  • [options.strict] «Boolean|String» overwrites the schema's strict mode option

  • [options.upsert=false] «Boolean» if true, and no documents found, insert a new document

  • [options.writeConcern=null] «Object» sets the write concern for replica sets. Overrides the schema-level write concern

  • [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is undefined when casting an update. In other words, if this is set, Mongoose will delete baz from the update in db.updateOne({}, { foo: 'bar', baz: undefined }) before sending the update to the server.

  • [options.timestamps=null] «Boolean» If set to false and schema-level timestamps are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.

  • [callback] «Function» function(error, res) {} where res has 3 properties: n, nModified, ok.

# Returns:
  • «Query»

Same as update(), except MongoDB replace the existing document with the given document (no atomic operators like $set).

# Example:

const res = await db.replaceOne({ _id: 24601 }, { name: 'Jean Valjean' });
res.n; // Number of documents matched
res.nModified; // Number of documents modified

This function triggers the following middleware.

  • replaceOne()

# db.update()

# Parameters
  • filter «Object»

  • doc «Object»

  • [options] «Object» optional see Query.prototype.setOptions()

  • [options.strict] «Boolean|String» overwrites the schema's strict mode option

  • [options.upsert=false] «Boolean» if true, and no documents found, insert a new document

  • [options.writeConcern=null] «Object» sets the write concern for replica sets. Overrides the schema-level write concern

  • [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is undefined when casting an update. In other words, if this is set, Mongoose will delete baz from the update in db.updateOne({}, { foo: 'bar', baz: undefined }) before sending the update to the server.

  • [options.multi=false] «Boolean» whether multiple documents should be updated or just the first one that matches filter.

  • [options.runValidators=false] «Boolean» if true, runs update validators on this command. Update validators validate the update operation against the model's schema.

  • [options.setDefaultsOnInsert=false] «Boolean» if this and upsert are true, mongoose will apply the defaults specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on MongoDB's $setOnInsert operator.

  • [options.timestamps=null] «Boolean» If set to false and schema-level timestamps are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.

  • [options.overwrite=false] «Boolean» By default, if you don't include any update operators in doc, Mongoose will wrap doc in $set for you. This prevents you from accidentally overwriting the document. This option tells Mongoose to skip adding $set.

  • [callback] «Function» params are (error, writeOpResult)

  • [callback] «Function»

# Returns:
  • «Query»

Updates one document in the database without returning it.

This function triggers the following middleware.

  • update()

# Examples:

Mydb.update({ age: { $gt: 18 } }, { oldEnough: true }, fn);

const res = await Mydb.update({ name: 'Tobi' }, { ferret: true });
res.n; // Number of documents that matched `{ name: 'Tobi' }`
// Number of documents that were changed. If every doc matched already
// had `ferret` set to `true`, `nModified` will be 0.
res.nModified;

# Valid options:

  • strict (boolean): overrides the schema-level strict option for this update
  • upsert (boolean): whether to create the doc if it doesn't match (false)
  • writeConcern (object): sets the write concern for replica sets. Overrides the schema-level write concern
  • omitUndefined (boolean): If true, delete any properties whose value is undefined when casting an update. In other words, if this is set, Mongoose will delete baz from the update in db.updateOne({}, { foo: 'bar', baz: undefined }) before sending the update to the server.
  • multi (boolean): whether multiple documents should be updated (false)
  • runValidators: if true, runs update validators on this command. Update validators validate the update operation against the model's schema.
  • setDefaultsOnInsert (boolean): if this and upsert are true, mongoose will apply the defaults specified in the model's schema if a new document is created. This option only works on MongoDB >= 2.4 because it relies on MongoDB's $setOnInsert operator.
  • timestamps (boolean): If set to false and schema-level timestamps are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.
  • overwrite (boolean): disables update-only mode, allowing you to overwrite the doc (false)

All update values are cast to their appropriate SchemaTypes before being sent.

The callback function receives (err, rawResponse).

  • err is the error if any occurred
  • rawResponse is the full response from Mongo

# Note:

All top level keys which are not atomic operation names are treated as set operations:

# Example:

var query = { name: 'borne' };
db.update(query, { name: 'jason bourne' }, options, callback);

// is sent as
db.update(query, { $set: { name: 'jason bourne' }}, options, function(err, res));
// if overwrite option is false. If overwrite is true, sent without the $set wrapper.

This helps prevent accidentally overwriting all documents in your collection with { name: 'jason bourne' }.

# Note:

Be careful to not use an existing model instance for the update clause (this won't work and can cause weird behavior like infinite loops). Also, ensure that the update clause does not have an _id property, which causes Mongo to return a "Mod on _id not allowed" error.

# Note:

Mongoose casts values and runs setters when using update. The following features are not applied by default.

If you need document middleware and fully-featured validation, load the document first and then use save().

db.findOne({ name: 'borne' }, function (err, doc) {
  if (err) ..
  doc.name = 'jason bourne';
  doc.save(callback);
})

# db.updateMany()

# Parameters
  • filter «Object»

  • doc «Object»

  • [options] «Object» optional see Query.prototype.setOptions()

  • [options.strict] «Boolean|String» overwrites the schema's strict mode option

  • [options.upsert=false] «Boolean» if true, and no documents found, insert a new document

  • [options.writeConcern=null] «Object» sets the write concern for replica sets. Overrides the schema-level write concern

  • [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is undefined when casting an update. In other words, if this is set, Mongoose will delete baz from the update in db.updateOne({}, { foo: 'bar', baz: undefined }) before sending the update to the server.

  • [options.timestamps=null] «Boolean» If set to false and schema-level timestamps are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.

  • [callback] «Function» function(error, res) {} where res has 3 properties: n, nModified, ok.

# Returns:
  • «Query»

Same as update(), except MongoDB will update all documents that match filter (as opposed to just the first one) regardless of the value of the multi option.

Note updateMany will not fire update middleware. Use pre('updateMany') and post('updateMany') instead.

# Example:

const res = await db.updateMany({ name: /Stark$/ }, { isDeleted: true });
res.n; // Number of documents matched
res.nModified; // Number of documents modified

This function triggers the following middleware.

  • updateMany()

# db.updateOne()

# Parameters
  • filter «Object»

  • doc «Object»

  • [options] «Object» optional see Query.prototype.setOptions()

  • [options.strict] «Boolean|String» overwrites the schema's strict mode option

  • [options.upsert=false] «Boolean» if true, and no documents found, insert a new document

  • [options.writeConcern=null] «Object» sets the write concern for replica sets. Overrides the schema-level write concern

  • [options.omitUndefined=false] «Boolean» If true, delete any properties whose value is undefined when casting an update. In other words, if this is set, Mongoose will delete baz from the update in db.updateOne({}, { foo: 'bar', baz: undefined }) before sending the update to the server.

  • [options.timestamps=null] «Boolean» If set to false and schema-level timestamps are enabled, skip timestamps for this update. Does nothing if schema-level timestamps are not set.

  • [callback] «Function» params are (error, writeOpResult)

# Returns:
  • «Query»

Same as update(), except it does not support the multi or overwrite options.

  • MongoDB will update only the first document that matches filter regardless of the value of the multi option.
  • Use replaceOne() if you want to overwrite an entire document rather than using atomic operators like $set.

# Example:

const res = await db.updateOne({ name: 'Jean-Luc Picard' }, { ship: 'USS Enterprise' });
res.n; // Number of documents matched
res.nModified; // Number of documents modified

This function triggers the following middleware.

  • updateOne()

# db.watch()

# Parameters
# Returns:
  • «ChangeStream» mongoose-specific change stream wrapper, inherits from EventEmitter

Requires a replica set running MongoDB >= 3.6.0. Watches the underlying collection for changes using MongoDB change streams.

This function does not trigger any middleware. In particular, it does not trigger aggregate middleware.

# The ChangeStream object is an event emitter that emits the following events

  • 'change': A change occurred, see below example
  • 'error': An unrecoverable error occurred. In particular, change streams currently error out if they lose connection to the replica set primary. Follow this GitHub issue for updates.
  • 'end': Emitted if the underlying stream is closed
  • 'close': Emitted if the underlying stream is closed

# Example:

const doc = await db.create({ name: 'Ned Stark' });
const changeStream = db.watch().on('change', change => console.log(change));
// Will print from the above `console.log()`:
// { _id: { _data: ... },
//   operationType: 'delete',
//   ns: { db: 'mydb', coll: 'db' },
//   documentKey: { _id: 5a51b125c5500f5aa094c7bd } }
await doc.remove();

# db.where()

# Parameters
  • path «String»
  • [val] «Object» optional value
# Returns:
  • «Query»

Creates a Query, applies the passed conditions, and returns the Query.

For example, instead of writing:

db.find({age: {$gte: 21, $lte: 65}}, callback);

we can instead write:

db.where('age').gte(21).lte(65).exec(callback);

Since the Query class also supports where you can continue chaining

db
.where('age').gte(21).lte(65)
.where('name', /^b/i)
... etc