Mongoose#Collection()

Mongoose集合构造器

Mongoose#Connection()

Mongoose连接构造器

Mongoose#Document()

Mongoose文档构造器

Mongoose#Error()

MongooseError构造器

Mongoose#Model()

Mongoose模型构造器

Mongoose#Mongoose()

Mongoose构造器

The exports of the mongoose module is an instance of this class.

Example:

var mongoose = require('mongoose');
var mongoose2 = new mongoose.Mongoose();
Mongoose()

Mongoose constructor.

The exports object of the mongoose module is an instance of this class. Most apps will only use this one instance.

show code

Mongoose#Promise()

The Mongoose Promise constructor.

Mongoose#Query()

The Mongoose Query constructor.

()

Expose connection states for user-land

show code

Mongoose#Schema()

The Mongoose Schema constructor

Example:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CatSchema = new Schema(..);

Mongoose#SchemaType()

The Mongoose SchemaType constructor

Mongoose#VirtualType()

The Mongoose VirtualType constructor

Mongoose#connect(uri(s), [options], [callback])

Opens the default mongoose connection.

Parameters:

uri(s) <String> [options] <Object> [callback] <Function> Returns:

<Mongoose> this See:

Mongoose#createConnection

If arguments are passed, they are proxied to either #### Connection#open or #### Connection#openSet appropriately.

Options passed take precedence over options included in connection strings.

Example:

mongoose.connect('mongodb://user:pass@localhost:port/database');

// replica sets
var uri = 'mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port';
mongoose.connect(uri);

// with options
mongoose.connect(uri, options);

// connecting to multiple mongos
var uri = 'mongodb://hostA:27501,hostB:27501';
var opts = { mongos: true };
mongoose.connect(uri, opts);

show code

Mongoose#createConnection([uri], [options])

Creates a Connection instance.

Parameters:

[uri] <String> a mongodb:// URI [options] <Object> options to pass to the driver Returns:

<Connection> the created Connection object See:

Connection#open

Connection#openSet

Each connection instance maps to a single database. This method is helpful when mangaging multiple db connections.

If arguments are passed, they are proxied to either #### Connection#open or #### Connection#openSet appropriately. This means we can pass db, server, and replset options to the driver. Note that the safe option specified in your schema will overwrite the safe db option specified here unless you set your schemas safe option to undefined. See this for more information.

Options passed take precedence over options included in connection strings.

Example:

// with mongodb:// URI
db = mongoose.createConnection('mongodb://user:pass@localhost:port/database');

// and options
var opts = { db: { native_parser: true }}
db = mongoose.createConnection('mongodb://user:pass@localhost:port/database', opts);

// replica sets
db = mongoose.createConnection('mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port');

// and options
var opts = { replset: { strategy: 'ping', rs_name: 'testSet' }}
db = mongoose.createConnection('mongodb://user:pass@localhost:port/database,mongodb://anotherhost:port,mongodb://yetanother:port', opts);

// with [host, database_name[, port] signature
db = mongoose.createConnection('localhost', 'database', port)

// and options
var opts = { server: { auto_reconnect: false }, user: 'username', pass: 'mypassword' }
db = mongoose.createConnection('localhost', 'database', port, opts)

// initialize now, connect later
db = mongoose.createConnection();
db.open('localhost', 'database', port, [opts]);

show code

Mongoose#disconnect([fn])

Disconnects all connections.

Parameters:

[fn] <Function> called after all connection close. Returns:

<Mongoose> this show code

Mongoose#get(key)

Gets mongoose options

Parameters:

key <String> Example:

mongoose.get('test') // returns the 'test' value

Mongoose#model(name, [schema], [collection], [skipInit])

Defines a model or retrieves it.

Parameters:

name <String> model name [schema] <Schema> [collection] <String> name (optional, induced from model name) [skipInit] <Boolean> whether to skip initialization (defaults to false) Models defined on the mongoose instance are available to all connection created by the same mongoose instance.

Example:

var mongoose = require('mongoose');

// define an Actor model with this mongoose instance
mongoose.model('Actor', new Schema({ name: String }));

// create a new connection
var conn = mongoose.createConnection(..);

// retrieve the Actor model
var Actor = conn.model('Actor');

When no collection argument is passed, Mongoose produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option.

Example:

var schema = new Schema({ name: String }, { collection: 'actor' });

// or

schema.set('collection', 'actor');

// or

var collectionName = 'actor'
var M = mongoose.model('Actor', schema, collectionName)

show code

Mongoose#modelNames()

Returns an array of model names created on this instance of Mongoose.

Returns:

<Array> Note:

Does not include names of models created using connection.model().

show code

Mongoose#plugin(fn, [opts])

Declares a global plugin executed on all Schemas.

Parameters:

fn <Function> plugin callback [opts] <Object> optional options Returns:

<Mongoose> this See:

plugins Equivalent to calling .plugin(fn) on each Schema you create.

show code

Mongoose#set(key, value)

Sets mongoose options

Parameters:

key <String> value <String> Example:

mongoose.set('test', value) // sets the 'test' option to `value`

mongoose.set('debug', true) // enable logging collection methods + arguments to the console

show code

Mongoose#SchemaTypes

The various Mongoose SchemaTypes.

Note:

Alias of mongoose.Schema.Types for backwards compatibility.

show code See:

Schema.SchemaTypes

Mongoose#Types

The various Mongoose Types.

Example:

var mongoose = require('mongoose');
var array = mongoose.Types.Array;

Types:

ObjectId Buffer SubDocument Array DocumentArray Using this exposed access to the ObjectId type, we can construct ids on demand.

var ObjectId = mongoose.Types.ObjectId;
var id1 = new ObjectId;

show code

Mongoose#connection

The default connection of the mongoose module.

Example:

var mongoose = require('mongoose');
mongoose.connect(...);
mongoose.connection.on('error', cb);

This is the connection used by default for every model created using mongoose.model.

show code Returns:

<Connection>

Mongoose#mongo

The node-mongodb-native driver Mongoose uses.

show code

Mongoose#mquery

The mquery query builder Mongoose uses.

show code

Mongoose#version

The Mongoose version

show code connection.js Connection(base)

Connection constructor

Parameters:

base <Mongoose> a mongoose instance Inherits:

NodeJS EventEmitter Events:

connecting: Emitted when connection.{open,openSet}() is executed on this connection.

connected: Emitted when this connection successfully connects to the db. May be emitted multiple times in reconnected scenarios.

open: Emitted after we connected and onOpen is executed on all of this connections models.

disconnecting: Emitted when connection.close() was executed.

disconnected: Emitted after getting disconnected from the db.

close: Emitted after we disconnected and onClose executed on all of this connections models.

reconnected: Emitted after we connected and subsequently disconnected, followed by successfully another successfull connection.

error: Emitted when an error occurs on this connection.

fullsetup: Emitted in a replica-set scenario, when all nodes specified in the connection string are connected.

For practical reasons, a Connection equals a Db.

show code

Connection#close([callback])

Closes the connection

Parameters:

[callback] <Function> optional Returns:

<Connection> self show code

Connection#collection(name, [options])

Retrieves a collection, creating it if not cached.

Parameters:

name <String> of the collection [options] <Object> optional collection options Returns:

<Collection> collection instance Not typically needed by applications. Just talk to your collection through your model.

show code

Connection#model(name, [schema], [collection])

Defines or retrieves a model.

Parameters:

name <String> the model name [schema] <Schema> a schema. necessary when defining a model [collection] <String> name of mongodb collection (optional) if not given it will be induced from model name Returns:

<Model> The compiled model See:

Mongoose#model

var mongoose = require('mongoose'); var db = mongoose.createConnection(..); db.model('Venue', new Schema(..)); var Ticket = db.model('Ticket', new Schema(..)); var Venue = db.model('Venue'); When no collection argument is passed, Mongoose produces a collection name by passing the model name to the utils.toCollectionName method. This method pluralizes the name. If you don't like this behavior, either pass a collection name or set your schemas collection name option.

Example:

var schema = new Schema({ name: String }, { collection: 'actor' });

// or

schema.set('collection', 'actor');

// or

var collectionName = 'actor'
var M = conn.model('Actor', schema, collectionName)

show code

Connection#modelNames()

Returns an array of model names created on this connection.

Returns:

<Array> show code

Connection#open(connection_string, [database], [port], [options], [callback])

Opens the connection to MongoDB.

Parameters:

connection_string <String> mongodb://uri or the host to which you are connecting [database] <String> database name [port] <Number> database port [options] <Object> options [callback] <Function> See:

node-mongodb-native http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate options is a hash with the following possible properties:

config - passed to the connection config instance db - passed to the connection db instance server - passed to the connection server instance(s) replset - passed to the connection ReplSet instance user - username for authentication pass - password for authentication auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) Notes:

Mongoose forces the db option forceServerObjectId false and cannot be overridden. Mongoose defaults the server auto_reconnect options to true which can be overridden. See the node-mongodb-native driver instance for options that it understands.

Options passed take precedence over options included in connection strings.

show code

Connection#openSet(uris, [database], [options], [callback])

Opens the connection to a replica set.

Parameters:

uris <String> comma-separated mongodb:// URIs [database] <String> database name if not included in uris [options] <Object> passed to the internal driver [callback] <Function> See:

node-mongodb-native http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate Example:

var db = mongoose.createConnection();
db.openSet("mongodb://user:pwd@localhost:27020/testing,mongodb://example.com:27020,mongodb://localhost:27019");

The database name and/or auth need only be included in one URI. The options is a hash which is passed to the internal driver connection object.

Valid options

db - passed to the connection db instance server - passed to the connection server instance(s) replset - passed to the connection ReplSetServer instance user - username for authentication pass - password for authentication auth - options for authentication (see http://mongodb.github.com/node-mongodb-native/api-generated/db.html#authenticate) mongos - Boolean - if true, enables High Availability support for mongos Options passed take precedence over options included in connection strings.

Notes:

If connecting to multiple mongos servers, set the mongos option to true.

conn.open('mongodb://mongosA:27501,mongosB:27501', { mongos: true }, cb); Mongoose forces the db option forceServerObjectId false and cannot be overridden. Mongoose defaults the server auto_reconnect options to true which can be overridden. See the node-mongodb-native driver instance for options that it understands.

Options passed take precedence over options included in connection strings.

show code

Connection#collections

A hash of the collections associated with this connection

show code

Connection#db

The mongodb.Db instance, set when the connection is opened

show code

Connection#global

A hash of the global options that are associated with this connection

show code

Connection#readyState

Connection ready state

0 = disconnected 1 = connected 2 = connecting 3 = disconnecting Each state change emits its associated event name.

Example

conn.on('connected', callback); conn.on('disconnected', callback); show code error/messages.js MongooseError#messages

The default built-in validator error messages. These may be customized.

// customize within each schema or globally like so var mongoose = require('mongoose'); mongoose.Error.messages.String.enum = "Your custom message for {PATH}."; As you might have noticed, error messages support basic templating

{PATH} is replaced with the invalid document path {VALUE} is replaced with the invalid value {TYPE} is replaced with the validator type such as "regexp", "min", or "user defined" {MIN} is replaced with the declared min value for the Number.min validator {MAX} is replaced with the declared max value for the Number.max validator Click the "show code" link below to see all defaults.

show code error/validation.js ValidationError#toString()

Console.log helper

show code drivers/node-mongodb-native/connection.js Native#### Connection#useDb(name)

Switches to a different database using the same connection pool.

Parameters:

name <String> The database name Returns:

<Connection> New Connection Object Returns a new connection object, with the new db.

show code NativeConnection.STATES

Expose the possible connection states.

show code drivers/node-mongodb-native/collection.js NativeCollection#getIndexes(callback)

Retreives information about this collections indexes.

Parameters:

callback <Function> document.js

Document#equals(doc)

Returns true if the Document stores the same data as doc.

Parameters:

doc <Document> a document to compare Returns:

<Boolean> Documents are considered equal when they have matching _ids, unless neither document has an _id, in which case this function falls back to using deepEqual().

show code

Document#execPopulate()

Explicitly executes population and returns a promise. Useful for ES6 integration.

Returns:

<Promise> promise that resolves to the document when population is done See:

Document.populate Example:

var promise = doc.
  populate('company').
  populate({
    path: 'notes',
    match: /airline/,
    select: 'text',
    model: 'modelName'
    options: opts
  }).
  execPopulate();

// summary
doc.execPopulate()

NOTE:

Population does not occur unless a callback is passed. Passing the same path a second time will overwrite the previous path options. See Model.populate() for explaination of options.

show code

Document#get(path, [type])

Returns the value of a path.

Parameters:

path <String> [type] <Schema, String, Number, Buffer, etc..> optionally specify a type for on-the-fly attributes Example

// path doc.get('age') // 47

// dynamic casting to a string doc.get('age', String) // "47" show code

Document#inspect()

Helper for console.log

show code

Document#invalidate(path, errorMsg, value)

Marks a path as invalid, causing validation to fail.

Parameters:

path <String> the field to invalidate errorMsg <String, Error> the error which states the reason path was invalid value <Object, String, Number, T> optional invalid value The errorMsg argument will become the message of the ValidationError.

The value argument (if passed) will be available through the ValidationError.value property.

doc.invalidate('size', 'must be less than 20', 14);

doc.validate(function (err) {
  console.log(err)
  // prints
  { message: 'Validation failed',
    name: 'ValidationError',
    errors:
     { size:
        { message: 'must be less than 20',
          name: 'ValidatorError',
          path: 'size',
          type: 'user defined',
          value: 14 } } }
})

show code

Document#isDirectModified(path)

Returns true if path was directly set and modified, else false.

Parameters:

path <String> Returns:

<Boolean> Example

doc.set('documents.0.title', 'changed'); doc.isDirectModified('documents.0.title') // true doc.isDirectModified('documents') // false show code

Document#isInit(path)

Checks if path was initialized.

Parameters:

path <String> Returns:

<Boolean> show code

Document#isModified([path])

Returns true if this document was modified, else false.

Parameters:

[path] <String> optional Returns:

<Boolean> If path is given, checks if a path or any full path containing path as part of its path chain has been modified.

Example

doc.set('documents.0.title', 'changed');
doc.isModified()                    // true
doc.isModified('documents')         // true
doc.isModified('documents.0.title') // true
doc.isDirectModified('documents')   // false

show code

Document#isSelected(path)

Checks if path was selected in the source query which initialized this document.

Parameters:

path <String> Returns:

<Boolean> Example

Thing.findOne().select('name').exec(function (err, doc) {
   doc.isSelected('name') // true
   doc.isSelected('age')  // false
})

show code

Document#markModified(path)

Marks the path as having pending changes to write to the db.

Parameters:

path <String> the path to mark modified Very helpful when using Mixed types.

Example:

doc.mixed.type = 'changed';
doc.markModified('mixed.type');
doc.save() // changes to mixed.type are now persisted

show code

Document#modifiedPaths()

Returns the list of paths that have been modified.

Returns:

<Array> show code

Document#populate([path], [callback])

Populates document references, executing the callback when complete.

Parameters:

[path] <String, Object> The path to populate or an options object [callback] <Function> When passed, population is invoked Returns:

<Document> this See:

Model.populate Example:

doc
.populate('company')
.populate({
  path: 'notes',
  match: /airline/,
  select: 'text',
  model: 'modelName'
  options: opts
}, function (err, user) {
  assert(doc._id == user._id) // the document itself is passed
})

// summary
doc.populate(path)               // not executed
doc.populate(options);           // not executed
doc.populate(path, callback)     // executed
doc.populate(options, callback); // executed
doc.populate(callback);          // executed

NOTE:

Population does not occur unless a callback is passed or you explicitly call execPopulate(). Passing the same path a second time will overwrite the previous path options. See Model.populate() for explaination of options.

show code

Document.prototype.populate = function populate () {
  if (0 === arguments.length) return this;

  var pop = this.$__.populate || (this.$__.populate = {});
  var args = utils.args(arguments);
  var fn;

  if ('function' == typeof args[args.length-1]) {
    fn = args.pop();
  }

  // allow `doc.populate(callback)`
  if (args.length) {
    // use hash to remove duplicate paths
    var res = utils.populate.apply(null, args);
    for (var i = 0; i `< res.length; ++i) {
      pop[res[i].path] = res[i];
    }
  }

  if (fn) {
    var paths = utils.object.vals(pop);
    this.$__.populate = undefined;
    this.constructor.populate(this, paths, fn);
  }

  return this;
};

Document#populated(path)

Gets _id(s) used during population of the given path.

Parameters:

path <String> Returns:

<Array, ObjectId, Number, Buffer, String, undefined> Example:

Model.findOne().populate('author').exec(function (err, doc) {
  console.log(doc.author.name)         // Dr.Seuss
  console.log(doc.populated('author')) // '5144cf8050f071d979c118a7'
})

If the path was not populated, undefined is returned.

show code

Document#set(path, val, [type], [options])

Sets the value of a path, or many paths.

Parameters:

path <String, Object> path or object of key/vals to set val <Any> the value to set [type] <Schema, String, Number, Buffer, etc..> optionally specify a type for "on-the-fly" attributes [options] <Object> optionally specify options that modify the behavior of the set Example:

// path, value
doc.set(path, value)

// object
doc.set({
    path  : value
  , path2 : {
       path  : value
    }
})

// only-the-fly cast to number
doc.set(path, value, Number)

// only-the-fly cast to string
doc.set(path, value, String)

// changing strict mode behavior
doc.set(path, value, { strict: false });

show code

Document#toJSON(options)

The return value of this method is used in calls to JSON.stringify(doc).

Parameters:

options <Object> Returns:

<Object> See:

Document#toObject

This method accepts the same options as #### Document#toObject. To apply the options to every document of your schema by default, set your schemas toJSON option to the same argument.

schema.set('toJSON', { virtuals: true }) See schema options for details.

show code

Document#toObject([options])

Converts this document into a plain javascript object, ready for storage in MongoDB.

Parameters:

[options] <Object> Returns:

<Object> js object See:

mongodb.Binary Buffers are converted to instances of mongodb.Binary for proper storage.

Options:

getters apply all getters (path and virtual getters) virtuals apply virtual getters (can override getters option) minimize remove empty objects (defaults to true) transform a transform function to apply to the resulting document before returning depopulate depopulate any populated paths, replacing them with their original refs (defaults to false) Getters/Virtuals

Example of only applying path getters

doc.toObject({ getters: true, virtuals: false }) Example of only applying virtual getters

doc.toObject({ virtuals: true }) Example of applying both path and virtual getters

doc.toObject({ getters: true }) To apply these options to every document of your schema by default, set your schemas toObject option to the same argument.

schema.set('toObject', { virtuals: true }) Transform

We may need to perform a transformation of the resulting object based on some criteria, say to remove some sensitive information or return a custom object. In this case we set the optional transform function.

Transform functions receive three arguments

function (doc, ret, options) {} doc The mongoose document which is being converted ret The plain object representation which has been converted options The options in use (either schema options or the options passed inline) Example

// specify the transform schema option if (!schema.options.toObject) schema.options.toObject = {}; schema.options.toObject.transform = function (doc, ret, options) { // remove the _id of every document before returning the result delete ret._id; }

// without the transformation in the schema doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }

// with the transformation doc.toObject(); // { name: 'Wreck-it Ralph' } With transformations we can do a lot more than remove properties. We can even return completely new customized objects:

if (!schema.options.toObject) schema.options.toObject = {}; schema.options.toObject.transform = function (doc, ret, options) { return { movie: ret.name } }

// without the transformation in the schema doc.toObject(); // { _id: 'anId', name: 'Wreck-it Ralph' }

// with the transformation doc.toObject(); // { movie: 'Wreck-it Ralph' } Note: if a transform function returns undefined, the return value will be ignored.

Transformations may also be applied inline, overridding any transform set in the options:

function xform (doc, ret, options) { return { inline: ret.name, custom: true } }

// pass the transform as an inline option doc.toObject({ transform: xform }); // { inline: 'Wreck-it Ralph', custom: true } Note: if you call toObject and pass any options, the transform declared in your schema options will not be applied. To force its application pass transform: true

if (!schema.options.toObject) schema.options.toObject = {}; schema.options.toObject.hide = '_id'; schema.options.toObject.transform = function (doc, ret, options) { if (options.hide) { options.hide.split(' ').forEach(function (prop) { delete ret[prop]; }); } }

var doc = new Doc({ _id: 'anId', secret: 47, name: 'Wreck-it Ralph' }); doc.toObject(); // { secret: 47, name: 'Wreck-it Ralph' } doc.toObject({ hide: 'secret _id' }); // { _id: 'anId', secret: 47, name: 'Wreck-it Ralph' } doc.toObject({ hide: 'secret _id', transform: true }); // { name: 'Wreck-it Ralph' } Transforms are applied to the document and each of its sub-documents. To determine whether or not you are currently operating on a sub-document you might use the following guard:

if ('function' == typeof doc.ownerDocument) { // working with a sub doc } Transforms, like all of these options, are also available for toJSON.

See schema options for some more details.

During save, no custom options are applied to the document before being sent to the database.

show code

Document#toString()

Helper for console.log

Document#update(doc, options, callback)

Sends an update command with this document _id as the query selector.

Parameters:

doc <Object> options <Object> callback <Function> Returns:

<Query> See:

Model.update Example:

weirdCar.update({$inc: {wheels:1}}, { w: 1 }, callback);

Valid options:

same as in Model.update show code

Document#validate(optional)

Executes registered validation rules for this document.

Parameters:

optional <Function> cb called after validation completes, passing an error if one occurred Returns:

<Promise> Promise Note:

This method is called pre save and if a validation rule is violated, save is aborted and the error is returned to your callback.

Example:

doc.validate(function (err) {
  if (err) handleError(err);
  else // validation passed
});

show code

Document#validateSync()

Executes registered validation rules (skipping asynchronous validators) for this document.

Returns:

<MongooseError, undefined> MongooseError if there are errors during validation, or undefined if there is no error. Note:

This method is useful if you need synchronous validation.

Example:

var err = doc.validateSync();
if ( err ){
  handleError( err );
} else {
  // validation passed
}

show code

Document#errors

Hash containing current validation errors.

show code

Document#id

The string version of this documents _id.

Note:

This getter exists on all documents by default. The getter can be disabled by setting the id option of its Schema to false at construction time.

new Schema({ name: String }, { id: false }); show code See:

Schema options

Document#isNew

Boolean flag specifying if the document is new.

show code

Document#schema

The documents schema.

show code query.js

Query#$where(js)

Specifies a javascript function or expression to pass to MongoDBs query system.

Parameters:

js <String, Function> javascript string or function Returns:

<Query> this See:

$where Example

query.$where('this.comments.length === 10 || this.name.length === 5')

// or

query.$where(function () { return this.comments.length === 10 || this.name.length === 5; }) NOTE:

Only use $where when you have a condition that cannot be met using other MongoDB operators like $lt. Be sure to read about all of its caveats before using.

Query#all([path], val)

Specifies an $all query condition.

Parameters:

[path] <String> val <Number> See:

$all When called with one argument, the most recent path passed to where() is used.

Query#and(array)

Specifies arguments for a $and condition.

Parameters:

array <Array> array of conditions Returns:

<Query> this See:

$and Example

query.and([{ color: 'green' }, { status: 'ok' }])

Query#batchSize(val)

Specifies the batchSize option.

Parameters:

val <Number> See:

batchSize Example

query.batchSize(100) Note

Cannot be used with distinct()

Query#box(val, Upper)

Specifies a $box condition

Parameters:

val <Object> Upper <[Array]> Right Coords Returns:

<Query> this See:

$box within() #### Query#within http://www.mongodb.org/display/DOCS/Geospatial+Indexing Example

var lowerLeft = [40.73083, -73.99756] var upperRight= [40.741404, -73.988135]

query.where('loc').within().box(lowerLeft, upperRight) query.box({ ll : lowerLeft, ur : upperRight })

Query#cast(model, [obj])

Casts this query to the schema of model

Parameters:

model <Model> [obj] <Object> Returns:

<Object> Note

If obj is present, it is cast instead of this query.

show code

Query#center()

DEPRECATED Alias for circle

Deprecated. Use circle instead.

Query#centerSphere([path], val)

DEPRECATED Specifies a $centerSphere condition

Parameters:

[path] <String> val <Object> Returns:

<Query> this See:

http://www.mongodb.org/display/DOCS/Geospatial+Indexing $centerSphere Deprecated. Use circle instead.

Example

var area = { center: [50, 50], radius: 10 }; query.where('loc').within().centerSphere(area); show code

Query#circle([path], area)

Specifies a $center or $centerSphere condition.

Parameters:

[path] <String> area <Object> Returns:

<Query> this See:

$center $centerSphere $geoWithin http://www.mongodb.org/display/DOCS/Geospatial+Indexing Example

var area = { center: [50, 50], radius: 10, unique: true }
query.where('loc').within().circle(area)
// alternatively
query.circle('loc', area);

// spherical calculations
var area = { center: [50, 50], radius: 10, unique: true, spherical: true }
query.where('loc').within().circle(area)
// alternatively
query.circle('loc', area);

New in 3.7.0

Query#comment(val)

Specifies the comment option.

Parameters:

val <Number> See:

comment Example

query.comment('login query')

Note

Cannot be used with distinct()

Query#count([criteria], [callback])

Specifying this query as a count query.

Parameters:

[criteria] <Object> mongodb selector [callback] <Function> Returns:

<Query> this See:

count Passing a callback executes the query.

Example:

var countQuery = model.where({ 'color': 'black' }).count();

query.count({ color: 'black' }).count(callback)

query.count({ color: 'black' }, callback)

query.where('color', 'black').count(function (err, count) {
  if (err) return handleError(err);
  console.log('there are %d kittens', count);
})

show code

Query#distinct([criteria], [field], [callback])

Declares or executes a distict() operation.

Parameters:

[criteria] <Object, Query> [field] <String> [callback] <Function> Returns:

<Query> this See:

distinct Passing a callback executes the query.

Example

distinct(criteria, field, fn)
distinct(criteria, field)
distinct(field, fn)
distinct(field)
distinct(fn)
distinct()

show code

Query#elemMatch(path, criteria)

Specifies an $elemMatch condition

Parameters:

path <String, Object, Function> criteria <Object, Function> Returns:

<Query> this See:

$elemMatch Example

query.elemMatch('comment', { author: 'autobot', votes: {$gte: 5}})

query.where('comment').elemMatch({ author: 'autobot', votes: {$gte: 5}})

query.elemMatch('comment', function (elem) {
  elem.where('author').equals('autobot');
  elem.where('votes').gte(5);
})

query.where('comment').elemMatch(function (elem) {
  elem.where({ author: 'autobot' });
  elem.where('votes').gte(5);
})

Query#equals(val)

Specifies the complementary comparison value for paths specified with where()

Parameters:

val <Object> Returns:

<Query> this Example

User.where('age').equals(49);

// is the same as

User.where('age', 49);

Query#exec([operation], [callback])

Executes the query

Parameters:

[operation] <String, Function> [callback] <Function> Returns:

<Promise> Examples:

var promise = query.exec(); var promise = query.exec('update');

query.exec(callback); query.exec('find', callback); show code

Query#exists([path], val)

Specifies an $exists condition

Parameters:

[path] <String> val <Number> Returns:

<Query> this See:

$exists Example

// { name: { $exists: true }} Thing.where('name').exists() Thing.where('name').exists(true) Thing.find().exists('name')

// { name: { $exists: false }} Thing.where('name').exists(false); Thing.find().exists('name', false);

Query#find([criteria], [callback])

Finds documents.

Parameters:

[criteria] <Object> mongodb selector [callback] <Function> Returns:

<Query> this When no callback is passed, the query is not executed. When the query is executed, the result will be an array of documents.

Example

query.find({ name: 'Los Pollos Hermanos' }).find(callback) show code

Query#findOne([criteria], [callback])

Declares the query a findOne operation. When executed, the first found document is passed to the callback.

Parameters:

[criteria] <Object, Query> mongodb selector [callback] <Function> Returns:

<Query> this See:

findOne Passing a callback executes the query. The result of the query is a single document.

Example

var query = Kitten.where({ color: 'white' }); query.findOne(function (err, kitten) { if (err) return handleError(err); if (kitten) { // doc may be null if no document matched } }); show code

Query#findOneAndRemove([conditions], [options], [callback])

Issues a mongodb findAndModify remove command.

Parameters:

[conditions] <Object> [options] <Object> [callback] <Function> Returns:

<Query> this See:

mongodb Finds a matching document, removes it, passing the found document (if any) to the callback. Executes immediately if callback is passed.

Available options

sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update Examples

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

Query#findOneAndUpdate([query], [doc], [options], [callback])

Issues a mongodb findAndModify update command.

Parameters:

[query] <Object, Query> [doc] <Object> [options] <Object> [callback] <Function> Returns:

<Query> this See:

mongodb 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 immediately if callback is passed.

Available options

new: bool - true to return the modified document rather than the original. defaults to true upsert: bool - creates the object if it doesn't exist. defaults to false. sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update Examples

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

Query#geometry(object)

Specifies a $geometry condition

Parameters:

object <Object> Must contain a type property which is a String and a coordinates property which is an Array. See the examples. Returns:

<Query> this See:

$geometry
http://docs.mongodb.org/manual/release-notes/2.4/#new-geospatial-indexes-with-geojson-and-improved-spherical-geometry
http://www.mongodb.org/display/DOCS/Geospatial+Indexing
Example

var polyA = [[[ 10, 20 ], [ 10, 40 ], [ 30, 40 ], [ 30, 20 ]]]
query.where('loc').within().geometry({ type: 'Polygon', coordinates: polyA })

// or
var polyB = [[ 0, 0 ], [ 1, 1 ]]
query.where('loc').within().geometry({ type: 'LineString', coordinates: polyB })

// or
var polyC = [ 0, 0 ]
query.where('loc').within().geometry({ type: 'Point', coordinates: polyC })

// or
query.where('loc').intersects().geometry({ type: 'Point', coordinates: polyC })

The argument is assigned to the most recent path passed to where().

NOTE:

geometry() must come after either intersects() or within().

The object argument must contain type and coordinates properties.

  • type {String}
  • coordinates {Array}

Query#gt([path], val)

Specifies a $gt query condition.

Parameters:

[path] <String> val <Number> See:

$gt When called with one argument, the most recent path passed to where() is used.

Example

Thing.find().where('age').gt(21)

// or
Thing.find().gt('age', 21)

Query#gte([path], val)

Specifies a $gte query condition.

Parameters:

[path] <String> val <Number> See:

$gte When called with one argument, the most recent path passed to where() is used.

Query#hint(val)

Sets query hints.

Parameters:

val <Object> a hint object Returns:

<Query> this See:

$hint Example

query.hint({ indexA: 1, indexB: -1}) Note

Cannot be used with distinct()

Query#in([path], val)

Specifies an $in query condition.

Parameters:

[path] <String> val <Number> See:

$in When called with one argument, the most recent path passed to where() is used.

Query#intersects([arg])

Declares an intersects query for geometry().

Parameters:

[arg] <Object> Returns:

<Query> this See:

$geometry geoIntersects Example

query.where('path').intersects().geometry({
    type: 'LineString'
  , coordinates: [[180.0, 11.0], [180, 9.0]]
})

query.where('path').intersects({
    type: 'LineString'
  , coordinates: [[180.0, 11.0], [180, 9.0]]
})

NOTE:

MUST be used after where().

NOTE:

In Mongoose 3.7, intersects changed from a getter to a function. If you need the old syntax, use this.

Query#lean(bool)

Sets the lean option.

Parameters:

bool <Boolean> defaults to true Returns:

<Query> this Documents returned from queries with the lean option enabled are plain javascript objects, not MongooseDocuments. They have no save method, getters/setters or other Mongoose magic applied.

Example:

new Query().lean() // true
new Query().lean(true)
new Query().lean(false)

Model.find().lean().exec(function (err, docs) {
  docs[0] instanceof mongoose.Document // false
});

This is a great option in high-performance read-only scenarios, especially when combined with stream.

show code

Query#limit(val)

Specifies the maximum number of documents the query will return.

Parameters:

val <Number> Example

query.limit(20) Note

Cannot be used with distinct()

Query#lt([path], val)

Specifies a $lt query condition.

Parameters:

[path] <String> val <Number> See:

$lt When called with one argument, the most recent path passed to where() is used.

Query#lte([path], val)

Specifies a $lte query condition.

Parameters:

[path] <String> val <Number> See:

$lte When called with one argument, the most recent path passed to where() is used.

Query#maxDistance([path], val)

Specifies a $maxDistance query condition.

Parameters:

[path] <String> val <Number> See:

$maxDistance When called with one argument, the most recent path passed to where() is used.

Query#maxScan(val)

Specifies the maxScan option.

Parameters:

val <Number> See:

maxScan Example

query.maxScan(100) Note

Cannot be used with distinct()

Query#maxscan()

DEPRECATED Alias of maxScan

See:

maxScan

Query#merge(source)

Merges another Query or conditions object into this one.

Parameters:

source <Query, Object> Returns:

<Query> this When a Query is passed, conditions, field selection and options are merged.

New in 3.7.0

Query#mod([path], val)

Specifies a $mod condition

Parameters:

[path] <String> val <Number> Returns:

<Query> this See:

$mod

Query#ne([path], val)

Specifies a $ne query condition.

Parameters:

[path] <String> val <Number> See:

$ne When called with one argument, the most recent path passed to where() is used.

Query#near([path], val)

Specifies a $near or $nearSphere condition

Parameters:

[path] <String> val <Object> Returns:

<Query> this See:

$near $nearSphere $maxDistance http://www.mongodb.org/display/DOCS/Geospatial+Indexing These operators return documents sorted by distance.

Example

query.where('loc').near({ center: [10, 10] }); query.where('loc').near({ center: [10, 10], maxDistance: 5 }); query.where('loc').near({ center: [10, 10], maxDistance: 5, spherical: true }); query.near('loc', { center: [10, 10], maxDistance: 5 });

Query#nearSphere()

DEPRECATED Specifies a $nearSphere condition

See:

near() $near $nearSphere $maxDistance Example

query.where('loc').nearSphere({ center: [10, 10], maxDistance: 5 }); Deprecated. Use query.near() instead with the spherical option set to true.

Example

query.where('loc').near({ center: [10, 10], spherical: true }); show code

Query#nin([path], val)

Specifies an $nin query condition.

Parameters:

[path] <String> val <Number> See:

$nin When called with one argument, the most recent path passed to where() is used.

Query#nor(array)

Specifies arguments for a $nor condition.

Parameters:

array <Array> array of conditions Returns:

<Query> this See:

$nor Example

query.nor([{ color: 'green' }, { status: 'ok' }])

Query#or(array)

Specifies arguments for an $or condition.

Parameters:

array <Array> array of conditions Returns:

<Query> this See:

$or Example

query.or([{ color: 'red' }, { status: 'emergency' }])

Query#polygon([path], [coordinatePairs...])

Specifies a $polygon condition

Parameters:

[path] <String, Array> [coordinatePairs...] <Array, Object> Returns:

<Query> this See:

$polygon http://www.mongodb.org/display/DOCS/Geospatial+Indexing Example

query.where('loc').within().polygon([10,20], [13, 25], [7,15]) query.polygon('loc', [10,20], [13, 25], [7,15])

Query#populate(path, [select], [model], [match], [options])

Specifies paths which should be populated with other documents.

Parameters:

path <Object, String> either the path to populate or an object specifying all parameters [select] <Object, String> Field selection for the population query [model] <Model> The name of the model you wish to use for population. If not specified, the name is looked up from the Schema ref. [match] <Object> Conditions for the population query [options] <Object> Options for the population query (sort, etc) Returns:

<Query> this See:

population

Query#select

Model.populate Example:

Kitten.findOne().populate('owner').exec(function (err, kitten) {
  console.log(kitten.owner.name) // Max
})

Kitten.find().populate({
    path: 'owner'
  , select: 'name'
  , match: { color: 'black' }
  , options: { sort: { name: -1 }}
}).exec(function (err, kittens) {
  console.log(kittens[0].owner.name) // Zoopa
})

// alternatively
Kitten.find().populate('owner', 'name', null, {sort: { name: -1 }}).exec(function (err, kittens) {
  console.log(kittens[0].owner.name) // Zoopa
})

Paths are populated after the query executes and a response is received. A separate query is then executed for each path specified for population. After a response for each query has also been returned, the results are passed to the callback.

show code

Query#read(pref, [tags])

Determines the MongoDB nodes from which to read.

Parameters:

pref <String> one of the listed preference options or aliases [tags] <Array> optional tags for this query Returns:

<Query> this See:

mongodb driver Preferences:

primary - (default) Read from primary only. Operations will produce an error if primary is unavailable. Cannot be combined with tags. secondary Read from secondary if available, otherwise error. primaryPreferred Read from primary if available, otherwise a secondary. secondaryPreferred Read from a secondary if available, otherwise read from the primary. nearest All operations read from among the nearest candidates, but unlike other modes, this option will include both the primary and all secondaries in the random selection. Aliases

p primary pp primaryPreferred s secondary sp secondaryPreferred n nearest Example:

new Query().read('primary')
new Query().read('p')  // same as primary

new Query().read('primaryPreferred')
new Query().read('pp') // same as primaryPreferred

new Query().read('secondary')
new Query().read('s')  // same as secondary

new Query().read('secondaryPreferred')
new Query().read('sp') // same as secondaryPreferred

new Query().read('nearest')
new Query().read('n')  // same as nearest

// read from secondaries with matching tags
new Query().read('s', [{ dc:'sf', s: 1 },{ dc:'ma', s: 2 }])

Read more about how to use read preferrences here and here.

Query#regex([path], val)

Specifies a $regex query condition.

Parameters:

[path] <String> val <Number> See:

$regex When called with one argument, the most recent path passed to where() is used.

Query#remove([criteria], [callback])

Declare and/or execute this query as a remove() operation.

Parameters:

[criteria] <Object, Query> mongodb selector [callback] <Function> Returns:

<Query> this See:

remove Example

Model.remove({ artist: 'Anne Murray' }, callback) Note

The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call remove() and then execute it by using the exec() method.

// not executed
var query = Model.find().remove({ name: 'Anne Murray' })

// executed
query.remove({ name: 'Anne Murray' }, callback)
query.remove({ name: 'Anne Murray' }).remove(callback)

// executed without a callback (unsafe write)
query.exec()

// summary
query.remove(conds, fn); // executes
query.remove(conds)
query.remove(fn) // executes
query.remove()

show code

Query#select(arg)

Specifies which document fields to include or exclude

Parameters:

arg <Object, String> Returns:

<Query> this See:

SchemaType When using string syntax, prefixing a path with - will flag that path as excluded. When a path does not have the - prefix, it is included. Lastly, if a path is prefixed with +, it forces inclusion of the path, which is useful for paths excluded at the schema level.

Example

// include a and b, exclude c query.select('a b -c');

// or you may use object notation, useful when // you have keys already prefixed with a "-" query.select({a: 1, b: 1, c: 0});

// force inclusion of field excluded at schema level query.select('+path') NOTE:

Cannot be used with distinct().

v2 had slightly different syntax such as allowing arrays of field names. This support was removed in v3.

Query#selected()

Determines if field selection has been made.

Returns:

<Boolean>

Query#selectedExclusively()

Determines if exclusive field selection has been made.

Returns:

<Boolean> query.selectedExclusively() // false query.select('-name') query.selectedExclusively() // true query.selectedInclusively() // false

Query#selectedInclusively()

Determines if inclusive field selection has been made.

Returns:

<Boolean> query.selectedInclusively() // false query.select('name') query.selectedInclusively() // true

Query#setOptions(options)

Sets query options.

Parameters:

options <Object> Options:

tailable sort limit skip maxscan batchSize comment snapshot hint slaveOk lean * safe

  • denotes a query helper method is also available

show code

Query#size([path], val)

Specifies a $size query condition.

Parameters:

[path] <String> val <Number> See:

$size When called with one argument, the most recent path passed to where() is used.

Example

MyModel.where('tags').size(0).exec(function (err, docs) { if (err) return handleError(err);

assert(Array.isArray(docs)); console.log('documents with 0 tags', docs); })

Query#skip(val)

Specifies the number of documents to skip.

Parameters:

val <Number> See:

cursor.skip Example

query.skip(100).limit(20) Note

Cannot be used with distinct()

Query#slaveOk(v)

DEPRECATED Sets the slaveOk option.

Parameters:

v <Boolean> defaults to true Returns:

<Query> this See:

mongodb slaveOk read() Deprecated in MongoDB 2.2 in favor of read preferences.

Example:

query.slaveOk() // true
query.slaveOk(true)
query.slaveOk(false)
#### Query#slice([path], val)

Specifies a $slice projection for an array.

Parameters:

[path] <String> val <Number> number/range of elements to slice Returns:

<Query> this See:

mongodb $slice Example

query.slice('comments', 5) query.slice('comments', -5) query.slice('comments', [10, 5]) query.where('comments').slice(5) query.where('comments').slice([-10, 5])

Query#snapshot()

Specifies this query as a snapshot query.

Returns:

<Query> this See:

snapshot Example

query.snapshot() // true query.snapshot(true) query.snapshot(false) Note

Cannot be used with distinct()

Query#sort(arg)

Sets the sort order

Parameters:

arg <Object, String> Returns:

<Query> this See:

cursor.sort If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1.

If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with - which will be treated as descending.

Example

// sort by "field" ascending and "test" descending query.sort({ field: 'asc', test: -1 });

// equivalent query.sort('field -test'); Note

Cannot be used with distinct()

show code

Query#stream([options])

Returns a Node.js 0.8 style read stream interface.

Parameters:

[options] <Object> Returns:

<QueryStream> See:

QueryStream Example

// follows the nodejs 0.8 stream api Thing.find({ name: /^hello/ }).stream().pipe(res)

// manual streaming var stream = Thing.find({ name: /^hello/ }).stream();

stream.on('data', function (doc) { // do something with the mongoose document }).on('error', function (err) { // handle the error }).on('close', function () { // the stream is closed }); Valid options

transform: optional function which accepts a mongoose document. The return value of the function will be emitted on data. Example

// JSON.stringify all documents before emitting var stream = Thing.find().stream({ transform: JSON.stringify }); stream.pipe(writeStream); show code

Query#tailable(bool)

Sets the tailable option (for use with capped collections).

Parameters:

bool <Boolean> defaults to true See:

tailable Example

query.tailable() // true query.tailable(true) query.tailable(false) Note

Cannot be used with distinct()

show code

Query#toConstructor()

Converts this query to a customized, reusable query constructor with all arguments and options retained.

Returns:

<Query> subclass-of-Query Example

// Create a query for adventure movies and read from the primary // node in the replica-set unless it is down, in which case we'll // read from a secondary node. var query = Movie.find({ tags: 'adventure' }).read('primaryPreferred');

// create a custom Query constructor based off these settings var Adventure = query.toConstructor();

// Adventure is now a subclass of mongoose.Query and works the same way but with the // default query parameters and options set. Adventure().exec(callback)

// further narrow down our query results while still using the previous settings Adventure().where({ name: /^Life/ }).exec(callback);

// since Adventure is a stand-alone constructor we can also add our own // helper methods and getters without impacting global queries Adventure.prototype.startsWith = function (prefix) { this.where({ name: new RegExp('^' + prefix) }) return this; } Object.defineProperty(Adventure.prototype, 'highlyRated', { get: function () { this.where({ rating: { $gt: 4.5 }}); return this; } }) Adventure().highlyRated.startsWith('Life').exec(callback) New in 3.7.3

show code

Query#update([criteria], [doc], [options], [callback])

Declare and/or execute this query as an update() operation.

Parameters:

[criteria] <Object> [doc] <Object> the update command [options] <Object> [callback] <Function> Returns:

<Query> this See:

Model.update update All paths passed that are not $atomic operations will become $set ops.

Example

Model.where({ _id: id }).update({ title: 'words' })

// becomes

Model.where({ _id: id }).update({ $set: { title: 'words' }}) Note

Passing an empty object {} as the doc will result in a no-op unless the overwrite option is passed. Without the overwrite option set, the update operation will be ignored and the callback executed without sending the command to MongoDB so as to prevent accidently overwritting documents in the collection.

Note

The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the exec() method.

var q = Model.where({ _id: id }); q.update({ $set: { name: 'bob' }}).update(); // not executed

q.update({ $set: { name: 'bob' }}).exec(); // executed as unsafe

// keys that are not $atomic ops become $set. // this executes the same command as the previous example. q.update({ name: 'bob' }).exec();

// overwriting with empty docs var q = Model.where({ _id: id }).setOptions({ overwrite: true }) q.update({ }, callback); // executes

// multi update with overwrite to empty doc var q = Model.where({ _id: id }); q.setOptions({ multi: true, overwrite: true }) q.update({ }); q.update(callback); // executed

// multi updates Model.where() .update({ name: /^match/ }, { $set: { arr: [] }}, { multi: true }, callback)

// more multi updates Model.where() .setOptions({ multi: true }) .update({ $set: { arr: [] }}, callback)

// single update by default Model.where({ email: '[email protected]' }) .update({ $inc: { counter: 1 }}, callback) API summary

update(criteria, doc, options, cb) // executes update(criteria, doc, options) update(criteria, doc, cb) // executes update(criteria, doc) update(doc, cb) // executes update(doc) update(cb) // executes update(true) // executes (unsafe write) update() show code

Query#where([path], [val])

Specifies a path for use with chaining.

Parameters:

[path] <String, Object> [val] <T> Returns:

<Query> this Example

// instead of writing: User.find({age: {$gte: 21, $lte: 65}}, callback);

// we can instead write: User.where('age').gte(21).lte(65);

// passing query conditions is permitted User.find().where({ name: 'vonderful' })

// chaining User .where('age').gte(21).lte(65) .where('name', /^vonderful/i) .where('friends').slice(10) .exec(callback)

Query#within()

Defines a $within or $geoWithin argument for geo-spatial queries.

Returns:

<Query> this See:

$polygon $box $geometry $center $centerSphere Example

query.where(path).within().box() query.where(path).within().circle() query.where(path).within().geometry()

query.where('loc').within({ center: [50,50], radius: 10, unique: true, spherical: true }); query.where('loc').within({ box: [[40.73, -73.9], [40.7, -73.988]] }); query.where('loc').within({ polygon: [[],[],[],[]] });

query.where('loc').within([], [], []) // polygon query.where('loc').within([], []) // box query.where('loc').within({ type: 'LineString', coordinates: [...] }); // geometry MUST be used after where().

NOTE:

As of Mongoose 3.7, $geoWithin is always used for queries. To change this behavior, see Query.use$geoWithin.

NOTE:

In Mongoose 3.7, within changed from a getter to a function. If you need the old syntax, use this.

Query#use$geoWithin

Flag to opt out of using $geoWithin.

mongoose.Query.use$geoWithin = false; MongoDB 2.4 deprecated the use of $within, replacing it with $geoWithin. Mongoose uses $geoWithin by default (which is 100% backward compatible with $within). If you are running an older version of MongoDB, set this flag to false so your within() queries continue to work.

show code See:

http://docs.mongodb.org/manual/reference/operator/geoWithin/ browser.js exports.Document()

The Mongoose browser Document constructor.

exports.Error()

The MongooseError constructor.

exports.Schema()

The Mongoose Schema constructor

Example:

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CatSchema = new Schema(..);
exports.VirtualType()

The Mongoose VirtualType constructor

exports#SchemaTypes

The various Mongoose SchemaTypes.

Note:

Alias of mongoose.Schema.Types for backwards compatibility.

show code See:

Schema.SchemaTypes exports#Types

The various Mongoose Types.

Example:

var mongoose = require('mongoose');
var array = mongoose.Types.Array;

Types:

ObjectId Buffer SubDocument Array DocumentArray Using this exposed access to the ObjectId type, we can construct ids on demand.

var ObjectId = mongoose.Types.ObjectId; var id1 = new ObjectId; show code virtualtype.js VirtualType()

VirtualType constructor

This is what mongoose uses to define virtual attributes via Schema.prototype.virtual.

Example:

var fullname = schema.virtual('fullname');

fullname instanceof mongoose.VirtualType // true show code

VirtualType#applyGetters(value, scope)

Applies getters to value using optional scope.

Parameters:

value <Object> scope <Object> Returns:

<T> the value after applying all getters show code

VirtualType#applySetters(value, scope)

Applies setters to value using optional scope.

Parameters:

value <Object> scope <Object> Returns:

<T> the value after applying all setters show code

VirtualType#get(fn)

Defines a getter.

Parameters:

fn <Function> Returns:

<VirtualType> this Example:

var virtual = schema.virtual('fullname');
virtual.get(function () {
  return this.name.first + ' ' + this.name.last;
});

show code

VirtualType#set(fn)

Defines a setter.

Parameters:

fn <Function> Returns:

<VirtualType> this Example:

var virtual = schema.virtual('fullname');
virtual.set(function (v) {
  var parts = v.split(' ');
  this.name.first = parts[0];
  this.name.last = parts[1];
});

show code schematype.js SchemaType(path, [options], [instance])

SchemaType constructor

Parameters:

path <String> [options] <Object> [instance] <String> show code

SchemaType#default(val)

Sets a default value for this SchemaType.

Parameters:

val <Function, T> the default value Returns:

<defaultValue> Example:

var schema = new Schema({ n: { type: Number, default: 10 })
var M = db.model('M', schema)
var m = new M;
console.log(m.n) // 10

Defaults can be either functions which return the value to use as the default or the literal value itself. Either way, the value will be cast based on its schema type before being set during document creation.

Example:

// values are cast:
var schema = new Schema({ aNumber: { type: Number, default: 4.815162342 }})
var M = db.model('M', schema)
var m = new M;
console.log(m.aNumber) // 4.815162342

// default unique objects for Mixed types:
var schema = new Schema({ mixed: Schema.Types.Mixed });
schema.path('mixed').default(function () {
  return {};
});

// if we don't use a function to return object literals for Mixed defaults,
// each document will receive a reference to the same object literal creating
// a "shared" object instance:
var schema = new Schema({ mixed: Schema.Types.Mixed });
schema.path('mixed').default({});
var M = db.model('M', schema);
var m1 = new M;
m1.mixed.added = 1;
console.log(m1.mixed); // { added: 1 }
var m2 = new M;
console.log(m2.mixed); // { added: 1 }

show code

SchemaType#get(fn)

Adds a getter to this schematype.

Parameters:

fn <Function> Returns:

<SchemaType> this Example:

function dob (val) {
  if (!val) return val;
  return (val.getMonth() + 1) + "/" + val.getDate() + "/" + val.getFullYear();
}

// defining within the schema
var s = new Schema({ born: { type: Date, get: dob })

// or by retreiving its SchemaType
var s = new Schema({ born: Date })
s.path('born').get(dob)

Getters allow you to transform the representation of the data as it travels from the raw mongodb document to the value that you see.

Suppose you are storing credit card numbers and you want to hide everything except the last 4 digits to the mongoose user. You can do so by defining a getter in the following way:

function obfuscate (cc) {
  return '****-****-****-' + cc.slice(cc.length-4, cc.length);
}

var AccountSchema = new Schema({
  creditCardNumber: { type: String, get: obfuscate }
});

var Account = db.model('Account', AccountSchema);

Account.findById(id, function (err, found) {
  console.log(found.creditCardNumber); // '****-****-****-1234'
});

Getters are also passed a second argument, the schematype on which the getter was defined. This allows for tailored behavior based on options passed in the schema.

function inspector (val, schematype) {
  if (schematype.options.required) {
    return schematype.path + ' is required';
  } else {
    return schematype.path + ' is not';
  }
}

var VirusSchema = new Schema({
  name: { type: String, required: true, get: inspector },
  taxonomy: { type: String, get: inspector }
})

var Virus = db.model('Virus', VirusSchema);

Virus.findById(id, function (err, virus) {
  console.log(virus.name);     // name is required
  console.log(virus.taxonomy); // taxonomy is not
})

show code

SchemaType#index(options)

Declares the index options for this schematype.

Parameters:

options <Object, Boolean, String> Returns:

<SchemaType> this Example:

var s = new Schema({ name: { type: String, index: true })
var s = new Schema({ loc: { type: [Number], index: 'hashed' })
var s = new Schema({ loc: { type: [Number], index: '2d', sparse: true })
var s = new Schema({ loc: { type: [Number], index: { type: '2dsphere', sparse: true }})
var s = new Schema({ date: { type: Date, index: { unique: true, expires: '1d' }})
Schema.path('my.path').index(true);
Schema.path('my.date').index({ expires: 60 });
Schema.path('my.path').index({ unique: true, sparse: true });

NOTE:

Indexes are created in the background by default. Specify background: false to override.

Direction doesn't matter for single key indexes

show code

SchemaType#required(required, [message])

Adds a required validator to this schematype.

Parameters:

required <Boolean> enable/disable the validator [message] <String> optional custom error message Returns:

<SchemaType> this See:

Customized Error Messages Example:

var s = new Schema({ born: { type: Date, required: true })

// or with custom error message

var s = new Schema({ born: { type: Date, required: '{PATH} is required!' })

// or through the path API

Schema.path('name').required(true);

// with custom error messaging

Schema.path('name').required(true, 'grrr :( ');

show code

SchemaType#select(val)

Sets default select() behavior for this path.

Parameters:

val <Boolean> Returns:

<SchemaType> this Set to true if this path should always be included in the results, false if it should be excluded by default. This setting can be overridden at the query level.

Example:

T = db.model('T', new Schema({ x: { type: String, select: true }}));
T.find(..); // field x will always be selected ..
// .. unless overridden;
T.find().select('-x').exec(callback);

show code

SchemaType#set(fn)

Adds a setter to this schematype.

Parameters:

fn <Function> Returns:

<SchemaType> this Example:

function capitalize (val) {
  if ('string' != typeof val) val = '';
  return val.charAt(0).toUpperCase() + val.substring(1);
}

// defining within the schema
var s = new Schema({ name: { type: String, set: capitalize }})

// or by retreiving its SchemaType
var s = new Schema({ name: String })
s.path('name').set(capitalize)

Setters allow you to transform the data before it gets to the raw mongodb document and is set as a value on an actual key.

Suppose you are implementing user registration for a website. Users provide an email and password, which gets saved to mongodb. The email is a string that you will want to normalize to lower case, in order to avoid one email having more than one account -- e.g., otherwise, [email protected] can be registered for 2 accounts via [email protected] and [email protected].

You can set up email lower case normalization easily via a Mongoose setter.

function toLower (v) {
  return v.toLowerCase();
}

var UserSchema = new Schema({
  email: { type: String, set: toLower }
})

var User = db.model('User', UserSchema)

var user = new User({email: '[email protected]'})
console.log(user.email); // '[email protected]'

// or
var user = new User
user.email = '[email protected]'
console.log(user.email) // '[email protected]'

As you can see above, setters allow you to transform the data before it gets to the raw mongodb document and is set as a value on an actual key.

NOTE: we could have also just used the built-in lowercase: true SchemaType option instead of defining our own function.

new Schema({ email: { type: String, lowercase: true }}) Setters are also passed a second argument, the schematype on which the setter was defined. This allows for tailored behavior based on options passed in the schema.

function inspector (val, schematype) {
  if (schematype.options.required) {
    return schematype.path + ' is required';
  } else {
    return val;
  }
}

var VirusSchema = new Schema({
  name: { type: String, required: true, set: inspector },
  taxonomy: { type: String, set: inspector }
})

var Virus = db.model('Virus', VirusSchema);
var v = new Virus({ name: 'Parvoviridae', taxonomy: 'Parvovirinae' });

console.log(v.name);     // name is required
console.log(v.taxonomy); // Parvovirinae

show code

SchemaType#sparse(bool)

Declares a sparse index.

Parameters:

bool <Boolean> Returns:

<SchemaType> this Example:

var s = new Schema({ name: { type: String, sparse: true })
Schema.path('name').index({ sparse: true });

show code

SchemaType#text()

Declares a full text index.

Parameters:

<bool> Returns:

<SchemaType> this Example:

var s = new Schema({name : {type: String, text : true })
 Schema.path('name').index({text : true});

show code

SchemaType#unique(bool)

Declares an unique index.

Parameters:

bool <Boolean> Returns:

<SchemaType> this Example:

var s = new Schema({ name: { type: String, unique: true })
Schema.path('name').index({ unique: true });

NOTE: violating the constraint returns an E11000 error from MongoDB when saving, not a Mongoose validation error.

show code

SchemaType#validate(obj, [errorMsg], [type])

Adds validator(s) for this document path.

Parameters:

obj <RegExp, Function, Object> validator [errorMsg] <String> optional error message [type] <String> optional validator type Returns:

<SchemaType> this Validators always receive the value to validate as their first argument and must return Boolean. Returning false means validation failed.

The error message argument is optional. If not passed, the default generic error message template will be used.

Examples:

// make sure every value is equal to "something"
function validator (val) {
  return val == 'something';
}
new Schema({ name: { type: String, validate: validator }});

// with a custom error message

var custom = [validator, 'Uh oh, {PATH} does not equal "something".']
new Schema({ name: { type: String, validate: custom }});

// adding many validators at a time

var many = [
    { validator: validator, msg: 'uh oh' }
  , { validator: anotherValidator, msg: 'failed' }
]
new Schema({ name: { type: String, validate: many }});

// or utilizing SchemaType methods directly:

var schema = new Schema({ name: 'string' });
schema.path('name').validate(validator, 'validation of `{PATH}` failed with value `{VALUE}`');

Error message templates:

From the examples above, you may have noticed that error messages support baseic templating. There are a few other template keywords besides {PATH} and {VALUE} too. To find out more, details are available here

Asynchronous validation:

Passing a validator function that receives two arguments tells mongoose that the validator is an asynchronous validator. The first argument passed to the validator function is the value being validated. The second argument is a callback function that must called when you finish validating the value and passed either true or false to communicate either success or failure respectively.

schema.path('name').validate(function (value, respond) { doStuff(value, function () { ... respond(false); // validation failed }) }, '{PATH} failed validation.'); You might use asynchronous validators to retreive other documents from the database to validate against or to meet other I/O bound validation needs.

Validation occurs pre('save') or whenever you manually execute #### Document#validate.

If validation fails during pre('save') and no callback was passed to receive the error, an error event will be emitted on your Models associated db connection, passing the validation error object along.

var conn = mongoose.createConnection(..); conn.on('error', handleError);

var Product = conn.model('Product', yourSchema); var dvd = new Product(..); dvd.save(); // emits error on the conn above If you desire handling these errors at the Model level, attach an error listener to your Model and the event will instead be emitted there.

// registering an error listener on the Model lets us handle errors more locally Product.on('error', handleError); show code schema/date.js SchemaDate#expires(when)

Declares a TTL index (rounded to the nearest second) for Date types only.

Parameters:

when <Number, String> Returns:

<SchemaType> this This sets the expiresAfterSeconds index option available in MongoDB >`= 2.1.2. This index type is only compatible with Date types.

Example:

// expire in 24 hours
new Schema({ createdAt: { type: Date, expires: 60*60*24 }});
expires utilizes the ms module from guille allowing us to use a friendlier syntax:

Example:

// expire in 24 hours
new Schema({ createdAt: { type: Date, expires: '24h' }});

// expire in 1.5 hours
new Schema({ createdAt: { type: Date, expires: '1.5h' }});

// expire in 7 days
var schema = new Schema({ createdAt: Date });
schema.path('createdAt').expires('7d');
show code
SchemaDate#max(maximum, [message])

Sets a maximum date validator.

Parameters:

maximum `<Date>` date
[message] `<String>` optional custom error message
Returns:

<SchemaType> this See:

Customized Error Messages Example:

var s = new Schema({ d: { type: Date, max: Date('2014-01-01') })
var M = db.model('M', s)
var m = new M({ d: Date('2014-12-08') })
m.save(function (err) {
  console.error(err) // validator error
  m.d = Date('2013-12-31');
  m.save() // success
})

// custom error messages
// We can also use the special {MAX} token which will be replaced with the invalid value
var max = [Date('2014-01-01'), 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).'];
var schema = new Schema({ d: { type: Date, max: max })
var M = mongoose.model('M', schema);
var s= new M({ d: Date('2014-12-08') });
s.validate(function (err) {
  console.log(String(err)) // ValidationError: The value of path `d` (2014-12-08) exceeds the limit (2014-01-01).
})

show code SchemaDate#min(value, [message])

Sets a minimum date validator.

Parameters:

value <Date> minimum date [message] <String> optional custom error message Returns:

<SchemaType> this See:

Customized Error Messages Example:

var s = new Schema({ d: { type: Date, min: Date('1970-01-01') })
var M = db.model('M', s)
var m = new M({ d: Date('1969-12-31') })
m.save(function (err) {
  console.error(err) // validator error
  m.d = Date('2014-12-08');
  m.save() // success
})

// custom error messages
// We can also use the special {MIN} token which will be replaced with the invalid value
var min = [Date('1970-01-01'), 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).'];
var schema = new Schema({ d: { type: Date, min: min })
var M = mongoose.model('M', schema);
var s= new M({ d: Date('1969-12-31') });
s.validate(function (err) {
  console.log(String(err)) // ValidationError: The value of path `d` (1969-12-31) is before the limit (1970-01-01).
})
show code
schema/objectid.js
ObjectId#auto(turnOn)

Adds an auto-generated ObjectId default if turnOn is true.

Parameters:

turnOn <Boolean> auto generated ObjectId defaults Returns:

<SchemaType> this show code schema/number.js SchemaNumber#max(maximum, [message])

Sets a maximum number validator.

Parameters:

maximum <Number> number [message] <String> optional custom error message Returns:

<SchemaType> this See:

Customized Error Messages Example:

var s = new Schema({ n: { type: Number, max: 10 })
var M = db.model('M', s)
var m = new M({ n: 11 })
m.save(function (err) {
  console.error(err) // validator error
  m.n = 10;
  m.save() // success
})

// custom error messages
// We can also use the special {MAX} token which will be replaced with the invalid value
var max = [10, 'The value of path `{PATH}` ({VALUE}) exceeds the limit ({MAX}).'];
var schema = new Schema({ n: { type: Number, max: max })
var M = mongoose.model('Measurement', schema);
var s= new M({ n: 4 });
s.validate(function (err) {
  console.log(String(err)) // ValidationError: The value of path `n` (4) exceeds the limit (10).
})

show code SchemaNumber#min(value, [message])

Sets a minimum number validator.

Parameters:

value <Number> minimum number [message] <String> optional custom error message Returns:

<SchemaType> this See:

Customized Error Messages Example:

var s = new Schema({ n: { type: Number, min: 10 })
var M = db.model('M', s)
var m = new M({ n: 9 })
m.save(function (err) {
  console.error(err) // validator error
  m.n = 10;
  m.save() // success
})

// custom error messages
// We can also use the special {MIN} token which will be replaced with the invalid value
var min = [10, 'The value of path `{PATH}` ({VALUE}) is beneath the limit ({MIN}).'];
var schema = new Schema({ n: { type: Number, min: min })
var M = mongoose.model('Measurement', schema);
var s= new M({ n: 4 });
s.validate(function (err) {
  console.log(String(err)) // ValidationError: The value of path `n` (4) is beneath the limit (10).
})
show code
schema/string.js

SchemaString#enum([args...])

Adds an enum validator

Parameters:

[args...] <String, Object> enumeration values Returns:

<SchemaType> this See:

Customized Error Messages Example:

var states = 'opening open closing closed'.split(' ')
var s = new Schema({ state: { type: String, enum: states }})
var M = db.model('M', s)
var m = new M({ state: 'invalid' })
m.save(function (err) {
  console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`.
  m.state = 'open'
  m.save(callback) // success
})

// or with custom error messages
var enu = {
  values: 'opening open closing closed'.split(' '),
  message: 'enum validator failed for path `{PATH}` with value `{VALUE}`'
}
var s = new Schema({ state: { type: String, enum: enu })
var M = db.model('M', s)
var m = new M({ state: 'invalid' })
m.save(function (err) {
  console.error(String(err)) // ValidationError: enum validator failed for path `state` with value `invalid`
  m.state = 'open'
  m.save(callback) // success
})

show code

SchemaString#lowercase()

Adds a lowercase setter.

Returns:

<SchemaType> this Example:

var s = new Schema({ email: { type: String, lowercase: true }})
var M = db.model('M', s);
var m = new M({ email: '[email protected]' });
console.log(m.email) // [email protected]

show code

SchemaString#match(regExp, [message])

Sets a regexp validator.

Parameters:

regExp <RegExp> regular expression to test against [message] <String> optional custom error message Returns:

<SchemaType> this See:

Customized Error Messages Any value that does not pass regExp.test(val) will fail validation.

Example:

var s = new Schema({ name: { type: String, match: /^a/ }})
var M = db.model('M', s)
var m = new M({ name: 'I am invalid' })
m.validate(function (err) {
  console.error(String(err)) // "ValidationError: Path `name` is invalid (I am invalid)."
  m.name = 'apples'
  m.validate(function (err) {
    assert.ok(err) // success
  })
})

// using a custom error message
var match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ];
var s = new Schema({ file: { type: String, match: match }})
var M = db.model('M', s);
var m = new M({ file: 'invalid' });
m.validate(function (err) {
  console.log(String(err)) // "ValidationError: That file doesn't end in .html (invalid)"
})
Empty strings, undefined, and null values always pass the match validator. If you require these values, enable the required validator also.

var s = new Schema({ name: { type: String, match: /^a/, required: true }})

show code

SchemaString#trim()

Adds a trim setter.

Returns:

<SchemaType> this The string value will be trimmed when set.

Example:

var s = new Schema({ name: { type: String, trim: true }})
var M = db.model('M', s)
var string = ' some name '
console.log(string.length) // 11
var m = new M({ name: string })
console.log(m.name.length) // 9

show code

SchemaString#uppercase()

Adds an uppercase setter.

Returns:

<SchemaType> this Example:

var s = new Schema({ caps: { type: String, uppercase: true }})
var M = db.model('M', s);
var m = new M({ caps: 'an example' });
console.log(m.caps) // AN EXAMPLE
show code
querystream.js
QueryStream(query, [options])

Provides a Node.js 0.8 style ReadStream interface for Queries.

Parameters:

query <Query> [options] <Object> Inherits:

NodeJS Stream Events:

data: emits a single Mongoose document

error: emits when an error occurs during streaming. This will emit before the close event.

close: emits when the stream reaches the end of the cursor or an error occurs, or the stream is manually destroyed. After this event, no more events are emitted.

var stream = Model.find().stream();

stream.on('data', function (doc) {
  // do something with the mongoose document
}).on('error', function (err) {
  // handle the error
}).on('close', function () {
  // the stream is closed
});

The stream interface allows us to simply "plug-in" to other Node.js 0.8 style write streams.

Model.where('created').gte(twoWeeksAgo).stream().pipe(writeStream); Valid options

transform: optional function which accepts a mongoose document. The return value of the function will be emitted on data. Example

// JSON.stringify all documents before emitting var stream = Thing.find().stream({ transform: JSON.stringify }); stream.pipe(writeStream); NOTE: plugging into an HTTP response will not work out of the box. Those streams expect only strings or buffers to be emitted, so first formatting our documents as strings/buffers is necessary.

NOTE: these streams are Node.js 0.8 style read streams which differ from Node.js 0.10 style. Node.js 0.10 streams are not well tested yet and are not guaranteed to work.

show code

QueryStream#destroy([err])

Destroys the stream, closing the underlying cursor. No more events will be emitted.

Parameters:

[err] <Error> show code

QueryStream#pause()

Pauses this stream.

show code

QueryStream#pipe()

Pipes this query stream into another stream. This method is inherited from NodeJS Streams.

See:

NodeJS Example:

query.stream().pipe(writeStream [, options])

QueryStream#resume()

Resumes this stream.

show code

QueryStream#paused

Flag stating whether or not this stream is paused.

show code

QueryStream#readable

Flag stating whether or not this stream is readable.

show code error.js MongooseError(msg)

MongooseError constructor

Parameters:

msg <String> Error message Inherits:

Error show code MongooseError.messages

The default built-in validator error messages.

show code See:

Error.messages promise.js Promise(fn)

Promise constructor.

Parameters:

fn <Function> a function which will be called when the promise is resolved that accepts fn(err, ...){} as signature Inherits:

mpromise Events:

err: Emits when the promise is rejected

complete: Emits when the promise is fulfilled

Promises are returned from executed queries. Example:

var query = Candy.find({ bar: true });
var promise = query.exec();

show code

Promise#addBack(listener)

Adds a single function as a listener to both err and complete.

Parameters:

listener <Function> Returns:

<Promise> this It will be executed with traditional node.js argument position when the promise is resolved.

promise.addBack(function (err, args...) {
  if (err) return handleError(err);
  console.log('success');
})

Alias of mpromise#onResolve.

Deprecated. Use onResolve instead.

Promise#addCallback(listener)

Adds a listener to the complete (success) event.

Parameters:

listener <Function> Returns:

<Promise> this Alias of mpromise#onFulfill.

Deprecated. Use onFulfill instead.

Promise#addErrback(listener)

Adds a listener to the err (rejected) event.

Parameters:

listener <Function> Returns:

<Promise> this Alias of mpromise#onReject.

Deprecated. Use onReject instead.

Promise#complete(args)

Fulfills this promise with passed arguments.

Parameters:

args <T> Alias of mpromise#fulfill.

Deprecated. Use fulfill instead.

Promise#end()

Signifies that this promise was the last in a chain of then()s: if a handler passed to the call to then which produced this promise throws, the exception will go uncaught.

See:

mpromise#end Example:

var p = new Promise;
p.then(function(){ throw new Error('shucks') });
setTimeout(function () {
  p.fulfill();
  // error was caught and swallowed by the promise returned from
  // p.then(). we either have to always register handlers on
  // the returned promises or we can do the following...
}, 10);

// this time we use .end() which prevents catching thrown errors
var p = new Promise;
var p2 = p.then(function(){ throw new Error('shucks') }).end(); // &lt;--
setTimeout(function () {
  p.fulfill(); // throws "shucks"
}, 10);

Promise#error(err)

Rejects this promise with err.

Parameters:

err <Error, String> Returns:

<Promise> this If the promise has already been fulfilled or rejected, not action is taken.

Differs from #reject by first casting err to an Error if it is not instanceof Error.

show code function Object() { [native code] }#fulfill(args)

Fulfills this promise with passed arguments.

Parameters:

args <T> See:

https://github.com/aheckmann/mpromise#fulfill Promise#on(event, listener)

Adds listener to the event.

Parameters:

event <String> listener <Function> Returns:

<Promise> this See:

mpromise#on If event is either the success or failure event and the event has already been emitted, thelistener is called immediately and passed the results of the original emitted event.

Promise#reject(reason)

Rejects this promise with reason.

Parameters:

reason <Object, String, Error> Returns:

<Promise> this See:

mpromise#reject If the promise has already been fulfilled or rejected, not action is taken.

Promise#resolve([err], [val])

Resolves this promise to a rejected state if err is passed or a fulfilled state if no err is passed.

Parameters:

[err] <Error> error or null [val] <Object> value to fulfill the promise with If the promise has already been fulfilled or rejected, not action is taken.

err will be cast to an Error if not already instanceof Error.

NOTE: overrides mpromise#resolve to provide error casting.

show code Promise#then(onFulFill, onReject)

Creates a new promise and returns it. If onFulfill or onReject are passed, they are added as SUCCESS/ERROR callbacks to this promise after the nextTick.

Parameters:

onFulFill <Function> onReject <Function> Returns:

<Promise> newPromise See:

promises-A+ mpromise#then Conforms to promises/A+ specification.

Example:

var promise = Meetups.find({ tags: 'javascript' }).select('_id').exec();
promise.then(function (meetups) {
  var ids = meetups.map(function (m) {
    return m._id;
  });
  return People.find({ meetups: { $in: ids }).exec();
}).then(function (people) {
  if (people.length &lt; 10000) {
    throw new Error('Too few people!!!');
  } else {
    throw new Error('Still need more people!!!');
  }
}).then(null, function (err) {
  assert.ok(err instanceof Error);
});

utils.js exports.pluralization

Pluralization rules.

show code These rules are applied while processing the argument to toCollectionName.

exports.uncountables

Uncountable words.

show code These words are applied while processing the argument to toCollectionName.

schema.js Schema(definition)

Schema constructor.

Parameters:

definition <Object> Inherits:

NodeJS EventEmitter Events:

init: Emitted after the schema is compiled into a Model.

Example:

var child = new Schema({ name: String });
var schema = new Schema({ name: String, age: Number, children: [child] });
var Tree = mongoose.model('Tree', schema);

// setting schema options
new Schema({ name: String }, { _id: false, autoIndex: false })

Options:

autoIndex: bool - defaults to null (which means use the connection's autoIndex option) bufferCommands: bool - defaults to true capped: bool - defaults to false collection: string - no default id: bool - defaults to true _id: bool - defaults to true minimize: bool - controls #### Document#toObject behavior when called manually - defaults to true read: string safe: bool - defaults to true. shardKey: bool - defaults to null strict: bool - defaults to true toJSON - object - no default toObject - object - no default validateBeforeSave - bool - defaults to true versionKey: bool - defaults to "__v" Note:

When nesting schemas, (children in the example above), always declare the child schema first before passing it into its parent.

show code Schema#add(obj, prefix)

Adds key path / schema type pairs to this schema.

Parameters:

obj <Object> prefix <String> Example:

var ToySchema = new Schema;
ToySchema.add({ name: 'string', color: 'string', price: 'number' });
show code
Schema#eachPath(fn)

Iterates the schemas paths similar to Array#forEach.

Parameters:

fn <Function> callback function Returns:

<Schema> this The callback is passed the pathname and schemaType as arguments on each iteration.

show code Schema#get(key)

Gets a schema option.

Parameters:

key <String> option name show code Schema#index(fields, [options])

Defines an index (most likely compound) for this schema.

Parameters:

fields <Object> [options] <Object> Example

schema.index({ first: 1, last: -1 }) show code Schema#indexes()

Compiles indexes from fields and schema-level indexes

show code Schema#method(method, [fn])

Adds an instance method to documents constructed from Models compiled from this schema.

Parameters:

method <String, Object> name [fn] <Function> Example

var schema = kittySchema = new Schema(..);

schema.method('meow', function () { console.log('meeeeeoooooooooooow'); })

var Kitty = mongoose.model('Kitty', schema);

var fizz = new Kitty; fizz.meow(); // meeeeeooooooooooooow If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as methods.

schema.method({ purr: function () {} , scratch: function () {} });

// later fizz.purr(); fizz.scratch(); show code Schema#path(path, constructor)

Gets/sets schema paths.

Parameters:

path <String> constructor <Object> Sets a path (if arity 2) Gets a path (if arity 1)

Example

schema.path('name') // returns a SchemaType schema.path('name', Number) // changes the schemaType of name to Number show code Schema#pathType(path)

Returns the pathType of path for this schema.

Parameters:

path <String> Returns:

<String> Given a path, returns whether it is a real, virtual, nested, or ad-hoc/undefined path.

show code Schema#plugin(plugin, opts)

Registers a plugin for this schema.

Parameters:

plugin <Function> callback opts <Object> See:

plugins show code Schema#post(method, fn)

Defines a post hook for the document

Parameters:

method <String> name of the method to hook fn <Function> callback See:

hooks.js Post hooks fire on the event emitted from document instances of Models compiled from this schema.

var schema = new Schema(..); schema.post('save', function (doc) { console.log('this fired after a document was saved'); });

var Model = mongoose.model('Model', schema);

var m = new Model(..); m.save(function (err) { console.log('this fires after the post hook'); }); show code Schema#pre(method, callback)

Defines a pre hook for the document.

Parameters:

method <String> callback <Function> See:

hooks.js Example

var toySchema = new Schema(..);

toySchema.pre('save', function (next) { if (!this.created) this.created = new Date; next(); })

toySchema.pre('validate', function (next) { if (this.name != 'Woody') this.name = 'Woody'; next(); }) show code Schema#requiredPaths()

Returns an Array of path strings that are required by this schema.

Returns:

<Array> show code Schema#set(key, [value])

Sets/gets a schema option.

Parameters:

key <String> option name [value] <Object> if not passed, the current option value is returned show code Schema#static(name, fn)

Adds static "class" methods to Models compiled from this schema.

Parameters:

name <String> fn <Function> Example

var schema = new Schema(..); schema.static('findByName', function (name, callback) { return this.find({ name: name }, callback); });

var Drink = mongoose.model('Drink', schema); Drink.findByName('sanpellegrino', function (err, drinks) { // }); If a hash of name/fn pairs is passed as the only argument, each name/fn pair will be added as statics.

show code Schema#virtual(name, [options])

Creates a virtual type with the given name.

Parameters:

name <String> [options] <Object> Returns:

<VirtualType> show code Schema#virtualpath(name)

Returns the virtual type with the given name.

Parameters:

name <String> Returns:

<VirtualType> show code Schema.Types

The various built-in Mongoose Schema Types.

show code Example:

var mongoose = require('mongoose');
var ObjectId = mongoose.Schema.Types.ObjectId;

Types:

String Number Boolean | Bool Array Buffer Date ObjectId | Oid Mixed Using this exposed access to the Mixed SchemaType, we can use them in our schema.

var Mixed = mongoose.Schema.Types.Mixed; new mongoose.Schema({ _user: Mixed }) Schema.indexTypes()

The allowed index types

show code Schema.reserved

Reserved document keys.

show code Keys in this object are names that are rejected in schema declarations b/c they conflict with mongoose functionality. Using these key name will throw an error.

on, emit, _events, db, get, set, init, isNew, errors, schema, options, modelName, collection, _pres, _posts, toObject NOTE: Use of these terms as method names is permitted, but play at your own risk, as they may be existing mongoose document methods you are stomping on.

var schema = new Schema(..); schema.methods.init = function () {} // potentially breaking types/array.js MongooseArray#$pop()

Pops the array atomically at most one time per document save().

See:

mongodb NOTE:

Calling this mulitple times on an array before saving sends the same command as calling it once. This update is implemented using the MongoDB $pop method which enforces this restriction.

doc.array = [1,2,3];

var popped = doc.array.$pop(); console.log(popped); // 3 console.log(doc.array); // [1,2]

// no affect popped = doc.array.$pop(); console.log(doc.array); // [1,2]

doc.save(function (err) { if (err) return handleError(err);

// we saved, now $pop works again popped = doc.array.$pop(); console.log(popped); // 2 console.log(doc.array); // [1] }) MongooseArray#$shift()

Atomically shifts the array at most one time per document save().

See:

mongodb NOTE:

Calling this mulitple times on an array before saving sends the same command as calling it once. This update is implemented using the MongoDB $pop method which enforces this restriction.

doc.array = [1,2,3];

var shifted = doc.array.$shift(); console.log(shifted); // 1 console.log(doc.array); // [2,3]

// no affect shifted = doc.array.$shift(); console.log(doc.array); // [2,3]

doc.save(function (err) { if (err) return handleError(err);

// we saved, now $shift works again shifted = doc.array.$shift(); console.log(shifted ); // 2 console.log(doc.array); // [3] }) function Object() { [native code] }#addToSet([args...])

Adds values to the array if not already present.

Parameters:

[args...] <T> Returns:

<Array> the values that were added Example:

console.log(doc.array) // [2,3,4]
var added = doc.array.addToSet(4,5);
console.log(doc.array) // [2,3,4,5]
console.log(added)     // [5]
function Object() { [native code] }#indexOf(obj)

Return the index of obj or -1 if not found.

Parameters:

obj <Object> the item to look for Returns:

<Number> function Object() { [native code] }#inspect()

Helper for console.log

function Object() { [native code] }#nonAtomicPush([args...])

Pushes items to the array non-atomically.

Parameters:

[args...] <T> NOTE:

marks the entire array as modified, which if saved, will store it as a $set operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.

function Object() { [native code] }#pop()

Wraps Array#pop with proper change tracking.

See:

MongooseArray#$pop Note:

marks the entire array as modified which will pass the entire thing to $set potentially overwritting any changes that happen between when you retrieved the object and when you save it.

function Object() { [native code] }#pull([args...])

Pulls items from the array atomically.

Parameters:

[args...] <T> See:

mongodb Examples:

doc.array.pull(ObjectId)
doc.array.pull({ _id: 'someId' })
doc.array.pull(36)
doc.array.pull('tag 1', 'tag 2')

To remove a document from a subdocument array we may pass an object with a matching _id.

doc.subdocs.push({ _id: 4815162342 }) doc.subdocs.pull({ _id: 4815162342 }) // removed Or we may passing the _id directly and let mongoose take care of it.

doc.subdocs.push({ _id: 4815162342 }) doc.subdocs.pull(4815162342); // works function Object() { [native code] }#push([args...])

Wraps Array#push with proper change tracking.

Parameters:

[args...] <Object> MongooseArray#remove()

Alias of pull

See:

MongooseArray#pull mongodb function Object() { [native code] }#set()

Sets the casted val at index i and marks the array modified.

Returns:

<Array> this Example:

// given documents based on the following
var Doc = mongoose.model('Doc', new Schema({ array: [Number] }));

var doc = new Doc({ array: [2,3,4] })

console.log(doc.array) // [2,3,4]

doc.array.set(1,"5");
console.log(doc.array); // [2,5,4] // properly cast to number
doc.save() // the change is saved

// VS not using array#set
doc.array[1] = "5";
console.log(doc.array); // [2,"5",4] // no casting
doc.save() // change is not saved
function Object() { [native code] }#shift()

Wraps Array#shift with proper change tracking.

Example:

doc.array = [2,3];
var res = doc.array.shift();
console.log(res) // 2
console.log(doc.array) // [3]

Note:

marks the entire array as modified, which if saved, will store it as a $set operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.

function Object() { [native code] }#sort()

Wraps Array#sort with proper change tracking.

NOTE:

marks the entire array as modified, which if saved, will store it as a $set operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.

function Object() { [native code] }#splice()

Wraps Array#splice with proper change tracking and casting.

Note:

marks the entire array as modified, which if saved, will store it as a $set operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.

function Object() { [native code] }#toObject(options)

Returns a native js Array.

Parameters:

options <Object> Returns:

<Array> function Object() { [native code] }#unshift()

Wraps Array#unshift with proper change tracking.

Note:

marks the entire array as modified, which if saved, will store it as a $set operation, potentially overwritting any changes that happen between when you retrieved the object and when you save it.

types/buffer.js function Object() { [native code] }#copy(target)

Copies the buffer.

Parameters:

target <Buffer> Returns:

<MongooseBuffer> Note:

Buffer#copy does not mark target as modified so you must copy from a MongooseBuffer for it to work as expected. This is a work around since copy modifies the target, not this.

function Object() { [native code] }#equals(other)

Determines if this buffer is equals to other buffer

Parameters:

other <Buffer> Returns:

<Boolean> function Object() { [native code] }#subtype(subtype)

Sets the subtype option and marks the buffer modified.

Parameters:

subtype <Hex> See:

http://bsonspec.org/#/specification SubTypes:

var bson = require('bson') bson.BSON_BINARY_SUBTYPE_DEFAULT bson.BSON_BINARY_SUBTYPE_FUNCTION bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY bson.BSON_BINARY_SUBTYPE_UUID bson.BSON_BINARY_SUBTYPE_MD5 bson.BSON_BINARY_SUBTYPE_USER_DEFINED

doc.buffer.subtype(bson.BSON_BINARY_SUBTYPE_UUID);

function Object() { [native code] }#toObject([subtype])

Converts this buffer to its Binary type representation.

Parameters:

[subtype] <Hex> Returns:

<Binary> See:

http://bsonspec.org/#/specification SubTypes:

var bson = require('bson')
bson.BSON_BINARY_SUBTYPE_DEFAULT
bson.BSON_BINARY_SUBTYPE_FUNCTION
bson.BSON_BINARY_SUBTYPE_BYTE_ARRAY
bson.BSON_BINARY_SUBTYPE_UUID
bson.BSON_BINARY_SUBTYPE_MD5
bson.BSON_BINARY_SUBTYPE_USER_DEFINED

doc.buffer.toObject(bson.BSON_BINARY_SUBTYPE_USER_DEFINED);

function Object() { [native code] }#write()

Writes the buffer.

types/objectid.js ObjectId()

ObjectId type constructor

Example

var id = new mongoose.Types.ObjectId;
types/embedded.js

Embedded#### Document#inspect()

Helper for console.log

show code Embedded#### Document#invalidate(path, err)

Marks a path as invalid, causing validation to fail.

Parameters:

path <String> the field to invalidate err <String, Error> error which states the reason path was invalid Returns:

<Boolean> show code Embedded#### Document#markModified(path)

Marks the embedded doc modified.

Parameters:

path <String> the path which changed Example:

var doc = blogpost.comments.id(hexstring);
doc.mixed.type = 'changed';
doc.markModified('mixed.type');

show code Embedded#### Document#ownerDocument()

Returns the top level document of this sub-document.

Returns:

<Document> show code Embedded#### Document#parent()

Returns this sub-documents parent document.

show code Embedded#### Document#parentArray()

Returns this sub-documents parent array.

show code Embedded#### Document#remove([fn])

Removes the subdocument from its parent array.

Parameters:

[fn] <Function> show code types/documentarray.js function Object() { [native code] }#create(obj)

Creates a subdocument casted to this schema.

Parameters:

obj <Object> the value to cast to this arrays SubDocument schema This is the same subdocument constructor used for casting.

function Object() { [native code] }#id(id)

Searches array items for the first document with a matching _id.

Parameters:

id <ObjectId, String, Number, Buffer> Returns:

<EmbeddedDocument, null> the subdocument or null if not found. Example:

var embeddedDoc = m.array.id(some_id);
function Object() { [native code] }#inspect()

Helper for console.log

function Object() { [native code] }#toObject([options])

Returns a native js Array of plain js objects

Parameters:

[options] <Object> optional options to pass to each documents toObject method call during conversion Returns:

<Array> NOTE:

Each sub-document is converted to a plain object by calling its #toObject method.

model.js Model#$where(argument)

Creates a Query and specifies a $where condition.

Parameters:

argument <String, Function> is a javascript string or anonymous function Returns:

<Query> See:

Query.$where 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 Model.

Blog.$where('this.comments.length > 5').exec(function (err, docs) {}); Model(doc)

Model constructor

Parameters:

doc <Object> values with which to create the document Inherits:

Document Events:

error: If listening to this event, it is emitted when a document was saved without passing a callback and an error occurred. If not listening, the event bubbles to the connection used to create this Model.

index: Emitted after Model#ensureIndexes completes. If an error occurred it is passed with the event.

Provides the interface to MongoDB collections as well as creates document instances.

show code Model#increment()

Signal that we desire an increment of this documents version.

See:

versionKeys Example:

Model.findById(id, function (err, doc) {
  doc.increment();
  doc.save(function (err) { .. })
})
show code
Model#model(name)

Returns another Model instance.

Parameters:

name <String> model name Example:

var doc = new Tank;
doc.model('User').findById(id, callback);
show code
Model#remove((err,)

@description Removes this document from the db.

Parameters:

(err, <function> product)} [fn] optional callback Returns:

<Promise> Promise show code Model#save(product,)

@description Saves this document.

Parameters:

product, <function(err, > Number)} [fn] optional callback See:

middleware show code Model.aggregate([...], [callback])

Performs aggregations on the models collection.

show code Parameters:

[...] <Object, Array> aggregation pipeline operator(s) or operator array [callback] <Function> Returns:

<Aggregate, Promise> See:

Aggregate MongoDB If a callback is passed, the aggregate is executed and a Promise is returned. If a callback is not passed, the aggregate itself is returned.

Example:

// Find the max balance of all accounts
Users.aggregate(
    { $group: { _id: null, maxBalance: { $max: '$balance' }}}
  , { $project: { _id: 0, maxBalance: 1 }}
  , function (err, res) {
  if (err) return handleError(err);
  console.log(res); // [ { maxBalance: 98000 } ]
});

// Or use the aggregation pipeline builder.
Users.aggregate()
  .group({ _id: null, maxBalance: { $max: '$balance' } })
  .select('-id maxBalance')
  .exec(function (err, res) {
    if (err) return handleError(err);
    console.log(res); // [ { maxBalance: 98 } ]
});

NOTE:

Arguments are not cast to the model's schema because $project operators allow redefining the "shape" of the documents at any stage of the pipeline, which may leave documents in an incompatible format. The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned). Requires MongoDB >`= 2.1 Model.count(conditions, [callback])

Counts number of matching documents in a database collection.

show code Parameters:

conditions <Object> [callback] <Function> Returns:

<Query> Example:

Adventure.count({ type: 'jungle' }, function (err, count) {
  if (err) ..
  console.log('there are %d jungle adventures', count);
});
Model.create(doc(s), [fn])

Shortcut for creating a new Document that is automatically saved to the db if valid.

show code Parameters:

doc(s) <Array, Object...> [fn] <Function> callback Returns:

<Promise> Example:

// pass individual docs
Candy.create({ type: 'jelly bean' }, { type: 'snickers' }, function (err, jellybean, snickers) {
  if (err) // ...
});

// pass an array
var array = [{ type: 'jelly bean' }, { type: 'snickers' }];
Candy.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 = Candy.create({ type: 'jawbreaker' });
promise.then(function (jawbreaker) {
  // ...
})
Model.discriminator(name, schema)

Adds a discriminator type.

show code
Parameters:

name `<String>` discriminator model name
schema `<Schema>` discriminator model schema
Example:

function BaseSchema() { Schema.apply(this, arguments);

this.add({ name: String, createdAt: Date }); } util.inherits(BaseSchema, Schema);

var PersonSchema = new BaseSchema(); var BossSchema = new BaseSchema({ department: String });

var Person = mongoose.model('Person', PersonSchema); var Boss = Person.discriminator('Boss', BossSchema); Model.distinct(field, [conditions], [callback])

Creates a Query for a distinct operation.

show code Parameters:

field <String> [conditions] <Object> optional [callback] <Function> Returns:

<Query> Passing a callback immediately 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); Model.ensureIndexes([cb])

Sends ensureIndex commands to mongo for each index declared in the schema.

show code Parameters:

[cb] <Function> optional callback Returns:

<Promise> Example:

Event.ensureIndexes(function (err) {
  if (err) return handleError(err);
});
After completion, an index event is emitted on this Model passing an error if one occurred.

Example:

var eventSchema = new Schema({ thing: { type: 'string', unique: true }}) var Event = mongoose.model('Event', eventSchema);

Event.on('index', function (err) { if (err) console.error(err); // error occurred during index creation }) NOTE: It is not recommended that you run this in production. Index creation may impact database performance depending on your load. Use with caution.

The ensureIndex commands are not sent in parallel. This is to avoid the MongoError: cannot add index with a background operation in progress error. See this ticket for more information.

Model.find(conditions, [fields], [options], [callback])

Finds documents

show code Parameters:

conditions <Object> [fields] <Object> optional fields to select [options] <Object> optional [callback] <Function> Returns:

<Query> See:

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

Examples:

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

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

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

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

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

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

// using the promise returned from executing a query var query = MyModel.find({ name: /john/i }, null, { skip: 10 }); var promise = query.exec(); promise.addBack(function (err, docs) {}); Model.findById(id, [fields], [options], [callback])

Finds a single document by id.

show code Parameters:

id <ObjectId, HexId> objectid, or a value that can be casted to one [fields] <Object> optional fields to select [options] <Object> optional [callback] <Function> Returns:

<Query> See:

field selection lean queries The id is cast based on the Schema before sending the command.

Example:

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

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

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

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

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

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

// same as above
Adventure.findById(id, 'name').lean().exec(function (err, doc) {});
Model.findByIdAndRemove(id, [options], [callback])

Issue a mongodb findAndModify remove command by a documents id.

show code
Parameters:

id `<ObjectId, HexString>` ObjectId or string that can be cast to one
[options] `<Object>`
[callback] `<Function>`
Returns:

`<Query>`
See:

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

Executes immediately if callback is passed, else a Query object is returned.

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
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
Model.findByIdAndUpdate(id, [update], [options], [callback])

Issues a mongodb findAndModify update command by a documents id.

show code
Parameters:

id `<ObjectId, HexId>` an ObjectId or string that can be cast to one.
[update] `<Object>`
[options] `<Object>`
[callback] `<Function>`
Returns:

`<Query>`
See:

Model.findOneAndUpdate
mongodb
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 immediately if callback is passed else a Query object is returned.

Options:

new: bool - true to return the modified document rather than the original. defaults to true
upsert: bool - creates the object if it doesn't exist. defaults to false.
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
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
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 immediately if callback is passed else a Query object is returned.

Options:

new: bool - true to return the modified document rather than the original. defaults to true
upsert: bool - creates the object if it doesn't exist. defaults to false.
sort: if multiple docs are found by the conditions, sets the sort order to choose which doc to update
Note:

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

Example:

Model.findByIdAndUpdate(id, { name: 'jason borne' }, options, callback)

// is sent as Model.findByIdAndUpdate(id, { $set: { name: 'jason borne' }}, options, callback) This helps prevent accidentally overwriting your document with { name: 'jason borne' }.

Note:

Although values are cast to their appropriate types when using the findAndModify helpers, the following are not applied:

defaults setters validators middleware If you need those features, use the traditional approach of first retrieving the document.

Model.findById(id, function (err, doc) { if (err) .. doc.name = 'jason borne'; doc.save(callback); }) Model.findOne(conditions, [fields], [options], [callback])

Finds one document.

show code Parameters:

conditions <Object> [fields] <Object> optional fields to select [options] <Object> optional [callback] <Function> Returns:

<Query> See:

field selection lean queries The conditions are cast to their respective SchemaTypes before the command is sent.

Example:

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

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

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

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

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

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

// chaining findOne queries (same as above)
Adventure.findOne({ type: 'iphone' }).select('name').lean().exec(callback);
Model.findOneAndRemove(conditions, [options], [callback])

Issue a mongodb findAndModify remove command.

show code
Parameters:

conditions `<Object>`
[options] `<Object>`
[callback] `<Function>`
Returns:

`<Query>`
See:

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

Executes immediately if callback is passed else a Query object is returned.

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
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
Although values are cast to their appropriate types when using the findAndModify helpers, the following are not applied:

defaults
setters
validators
middleware
If you need those features, use the traditional approach of first retrieving the document.

Model.findById(id, function (err, doc) {
  if (err) ..
  doc.remove(callback);
})
Model.findOneAndUpdate([conditions], [update], [options], [callback])

Issues a mongodb findAndModify update command.

show code
Parameters:

[conditions] `<Object>`
[update] `<Object>`
[options] `<Object>`
[callback] `<Function>`
Returns:

`<Query>`
See:

mongodb
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 immediately if callback is passed else a Query object is returned.

Options:

new: bool - true to return the modified document rather than the original. defaults to true
upsert: bool - creates the object if it doesn't exist. defaults to false.
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
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' }; Model.findOneAndUpdate(query, { name: 'jason borne' }, options, callback)

// is sent as Model.findOneAndUpdate(query, { $set: { name: 'jason borne' }}, options, callback) This helps prevent accidentally overwriting your document with { name: 'jason borne' }.

Note:

Although values are cast to their appropriate types when using the findAndModify helpers, the following are not applied:

defaults setters validators middleware If you need those features, use the traditional approach of first retrieving the document.

Model.findOne({ name: 'borne' }, function (err, doc) { if (err) .. doc.name = 'jason borne'; doc.save(callback); }) Model.geoNear(GeoJSON, options, [callback])

geoNear support for Mongoose

show code Parameters:

GeoJSON <Object, Array> point or legacy coordinate pair [x,y] to search near options <Object> for the qurery [callback] <Function> optional callback for the query Returns:

<Promise> See:

http://docs.mongodb.org/manual/core/2dsphere/ http://mongodb.github.io/node-mongodb-native/api-generated/collection.html?highlight=geonear#geoNear Options:

lean {Boolean} return the raw object All options supported by the driver are also supported Example:

// Legacy point
Model.geoNear([1,3], { maxDistance : 5, spherical : true }, function(err, results, stats) {
   console.log(results);
});

// geoJson
var point = { type : "Point", coordinates : [9,9] };
Model.geoNear(point, { maxDistance : 5, spherical : true }, function(err, results, stats) {
   console.log(results);
});
Model.geoSearch(condition, options, [callback])

Implements $geoSearch functionality for Mongoose

show code
Parameters:

condition `<Object>` an object that specifies the match condition (required)
options `<Object>` for the geoSearch, some (near, maxDistance) are required
[callback] `<Function>` optional callback
Returns:

`<Promise>`
See:

http://docs.mongodb.org/manual/reference/command/geoSearch/
http://docs.mongodb.org/manual/core/geohaystack/
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 {Boolean} return the raw object instead of the Mongoose Model Model.hydrate(obj)

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.

show code Parameters:

obj <Object> Returns:

<Document> Example:

// hydrate previous data into a Mongoose document
var mongooseCandy = Candy.hydrate({ _id: '54108337212ffb6d459f854c', type: 'jelly bean' });
Model.mapReduce(o, [callback])

Executes a mapReduce command.

show code
Parameters:

o `<Object>` an object specifying map-reduce options
[callback] `<Function>` optional callback
Returns:

`<Promise>`
See:

http://www.mongodb.org/display/DOCS/MapReduce
o is an object specifying all mapReduce options as well as the map and reduce functions. All options are delegated to the driver implementation.

Example:

var o = {}; o.map = function () { emit(this.name, 1) } o.reduce = function (k, vals) { return vals.length } User.mapReduce(o, function (err, results) { console.log(results) }) Other options:

query {Object} query filter object. 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. 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 Model 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 = {};
o.map = function () { emit(this.name, 1) }
o.reduce = function (k, vals) { return vals.length }
o.out = { replace: 'createdCollectionNameForResults' }
o.verbose = true;

User.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);
  });
})

// a promise is returned so you may instead write
var promise = User.mapReduce(o);
promise.then(function (model, 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()
Model.populate(docs, options, [cb(err,doc)])

Populates document references.

show code
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.
[cb(err,doc)] `<Function>` Optional callback, executed upon completion. Receives `err` and the `doc(s)`.
Returns:

`<Promise>`
Available 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
Examples:

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

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

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

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

// imagine a Weapon model exists with two saved documents:
//   { _id: 389, name: 'whip' }
//   { _id: 8921, name: 'boomerang' }

var user = { name: 'Indiana Jones', weapon: 389 }
Weapon.populate(user, { path: 'weapon', model: 'Weapon' }, 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 })
Weapon.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 Weapon model because
// we were already using it's populate() method.
Model.remove(conditions, [callback])

Removes documents from the collection.

show code
Parameters:

conditions `<Object>`
[callback] `<Function>`
Returns:

`<Promise>` Promise
Example:

Comment.remove({ title: 'baby born from alien father' }, function (err) {

}); Note:

To remove documents without waiting for a response from MongoDB, do not pass a callback, then call exec on the returned Query:

var query = Comment.remove({ _id: id }); query.exec(); Note:

This method sends a remove command directly to MongoDB, no Mongoose documents are involved. Because no Mongoose documents are involved, no middleware (hooks) are executed.

Model.update(conditions, doc, [options], [callback])

Updates documents in the database without returning them.

show code Parameters:

conditions <Object> doc <Object> [options] <Object> [callback] <Function> Returns:

<Query> See:

strict Examples:

MyModel.update({ age: { $gt: 18 } }, { oldEnough: true }, fn); MyModel.update({ name: 'Tobi' }, { ferret: true }, { multi: true }, function (err, numberAffected, raw) { if (err) return handleError(err); console.log('The number of updated documents was %d', numberAffected); console.log('The raw response from Mongo was ', raw); }); Valid options:

safe (boolean) safe mode (defaults to value set in schema (true)) upsert (boolean) whether to create the doc if it doesn't match (false) multi (boolean) whether multiple documents should be updated (false) strict (boolean) overrides the strict option for this update 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, numberAffected, rawResponse).

err is the error if any occurred numberAffected is the count of updated documents Mongo reported 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' };
Model.update(query, { name: 'jason borne' }, options, callback)

// is sent as
Model.update(query, { $set: { name: 'jason borne' }}, options, callback)
// 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 borne' }.

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:

To update documents without waiting for a response from MongoDB, do not pass a callback, then call exec on the returned Query:

Comment.update({ _id: id }, { $set: { text: 'changed' }}).exec();
Note:

Although values are casted to their appropriate types when using update, the following are not applied:

defaults
setters
validators
middleware
If you need those features, use the traditional approach of first retrieving the document.

Model.findOne({ name: 'borne' }, function (err, doc) {
  if (err) ..
  doc.name = 'jason borne';
  doc.save(callback);
})
Model.where(path, [val])

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

show code
Parameters:

path `<String>`
[val] `<Object>` optional value
Returns:

`<Query>`
For example, instead of writing:

User.find({age: {$gte: 21, $lte: 65}}, callback);
we can instead write:

User.where('age').gte(21).lte(65).exec(callback);
Since the Query class also supports where you can continue chaining

User
.where('age').gte(21).lte(65)
.where('name', /^b/i)
... etc
Model#base

Base Mongoose instance the model uses.

show code
Model#collection

Collection the model uses.

show code
Model#db

Connection the model uses.

show code
Model#discriminators

Registered discriminators for this model.

show code
Model#modelName

The name of the model

show code
Model#schema

Schema the model uses.

show code
aggregate.js
Aggregate([ops])

Aggregate constructor used for building aggregation pipelines.

Parameters:

[ops] `<Object, Array>` aggregation operator(s) or operator array
See:

MongoDB
driver
Example:

new Aggregate(); new Aggregate({ $project: { a: 1, b: 1 } }); new Aggregate({ $project: { a: 1, b: 1 } }, { $skip: 5 }); new Aggregate([{ $project: { a: 1, b: 1 } }, { $skip: 5 }]); Returned when calling Model.aggregate().

Example:

Model
.aggregate({ $match: { age: { $gte: 21 }}})
.unwind('tags')
.exec(callback)
Note:

The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
Requires MongoDB >`= 2.1
show code
Aggregate#allowDiskUse(value, [tags])

Sets the allowDiskUse option for the aggregation query (ignored for `< 2.6.0)

Parameters:

value `<Boolean>` Should tell server it can use hard drive to store data during aggregation.
[tags] `<Array>` optional tags for this query
See:

mongodb
Example:

Model.aggregate(..).allowDiskUse(true).exec(callback) show code Aggregate#append(ops)

Appends new operators to this aggregate pipeline

Parameters:

ops <Object> operator(s) to append Returns:

<Aggregate> Examples:

aggregate.append({ $project: { field: 1 }}, { $limit: 2 });

// or pass an array var pipeline = [{ $match: { daw: 'Logic Audio X' }} ]; aggregate.append(pipeline); show code Aggregate#cursor(options)

Sets the cursor option option for the aggregation query (ignored for `< 2.6.0)

Parameters:

options <Object> set the cursor batch size See:

mongodb Example:

Model.aggregate(..).cursor({ batchSize: 1000 }).exec(callback)
show code
Aggregate#exec([callback])

Executes the aggregate pipeline on the currently bound Model.

Parameters:

[callback] `<Function>`
Returns:

`<Promise>`
See:

Promise
Example:

aggregate.exec(callback);

// Because a promise is returned, the callback is optional. var promise = aggregate.exec(); promise.then(..); show code Aggregate#group(arg)

Appends a new custom $group operator to this aggregate pipeline.

Parameters:

arg <Object> $group operator contents Returns:

<Aggregate> See:

$group Examples:

aggregate.group({ _id: "$department" }); Aggregate#limit(num)

Appends a new $limit operator to this aggregate pipeline.

Parameters:

num <Number> maximum number of records to pass to the next stage Returns:

<Aggregate> See:

$limit Examples:

aggregate.limit(10); Aggregate#match(arg)

Appends a new custom $match operator to this aggregate pipeline.

Parameters:

arg <Object> $match operator contents Returns:

<Aggregate> See:

$match Examples:

aggregate.match({ department: { $in: [ "sales", "engineering" } } }); Aggregate#near(parameters)

Appends a new $geoNear operator to this aggregate pipeline.

Parameters:

parameters <Object> Returns:

<Aggregate> See:

$geoNear NOTE:

MUST be used as the first operator in the pipeline.

Examples:

aggregate.near({ near: [40.724, -73.997], distanceField: "dist.calculated", // required maxDistance: 0.008, query: { type: "public" }, includeLocs: "dist.location", uniqueDocs: true, num: 5 }); Aggregate#project(arg)

Appends a new $project operator to this aggregate pipeline.

Parameters:

arg <Object, String> field specification Returns:

<Aggregate> See:

projection Mongoose query selection syntax is also supported.

Examples:

// include a, include b, exclude _id aggregate.project("a b -_id");

// or you may use object notation, useful when // you have keys already prefixed with a "-" aggregate.project({a: 1, b: 1, _id: 0});

// reshaping documents aggregate.project({ newField: '$b.nested' , plusTen: { $add: ['$val', 10]} , sub: { name: '$a' } })

// etc aggregate.project({ salary_k: { $divide: [ "$salary", 1000 ] } }); show code Aggregate#read(pref, [tags])

Sets the readPreference option for the aggregation query.

Parameters:

pref <String> one of the listed preference options or their aliases [tags] <Array> optional tags for this query See:

mongodb driver Example:

``` Model.aggregate(..).read('primaryPreferred').exec(callback) show code Aggregate#skip(num)

Appends a new $skip operator to this aggregate pipeline.

Parameters:

num <Number> number of records to skip before next stage Returns:

<Aggregate> See:

$skip Examples:

aggregate.skip(10); Aggregate#sort(arg)

Appends a new $sort operator to this aggregate pipeline.

Parameters:

arg <Object, String> Returns:

<Aggregate> this See:

$sort If an object is passed, values allowed are asc, desc, ascending, descending, 1, and -1.

If a string is passed, it must be a space delimited list of path names. The sort order of each path is ascending unless the path name is prefixed with - which will be treated as descending.

Examples:

// these are equivalent aggregate.sort({ field: 'asc', test: -1 }); aggregate.sort('field -test'); show code Aggregate#unwind(fields)

Appends new custom $unwind operator(s) to this aggregate pipeline.

Parameters:

fields <String> the field(s) to unwind Returns:

<Aggregate> See:

$unwind Examples:

aggregate.unwind("tags"); aggregate.unwind("a", "b", "c"); show code collection.js Collection(name, conn, opts)

Abstract Collection constructor

Parameters:

name <String> name of the collection conn <Connection> A MongooseConnection instance opts <Object> optional collection options This is the base class that drivers inherit from and implement.

show code Collection#ensureIndex()

Abstract method that drivers must implement.

show code Collection#find()

Abstract method that drivers must implement.

show code Collection#findAndModify()

Abstract method that drivers must implement.

show code Collection#findOne()

Abstract method that drivers must implement.

show code Collection#getIndexes()

Abstract method that drivers must implement.

show code Collection#insert()

Abstract method that drivers must implement.

show code Collection#mapReduce()

Abstract method that drivers must implement.

show code Collection#save()

Abstract method that drivers must implement.

show code Collection#update()

Abstract method that drivers must implement.

show code Collection#conn

The Connection instance

show code Collection#name

The collection name

show code

results matching ""

    No results matching ""