Mongoose#set()
docs Mongoose constructor.
The exports object of the mongoose
module is an instance of this class. Most apps will only use this one instance.
const mongoose = require('mongoose');
mongoose instanceof mongoose.Mongoose; // true
// Create a new Mongoose instance with its own `connect()`, `set()`, `model()`, etc.
const m = new mongoose.Mongoose();
The Mongoose Aggregate constructor
a.b.c
in the doc where this cast error occurred The Mongoose CastError constructor
The Mongoose Collection constructor
The Mongoose Connection constructor
The Mongoose Decimal128 SchemaType. Used for declaring paths in your schema that should be 128-bit decimal floating points. Do not use this to create a new Decimal128 instance, use mongoose.Types.Decimal128
instead.
const vehicleSchema = new Schema({ fuelLevel: mongoose.Decimal128 });
The Mongoose Document constructor.
The Mongoose DocumentProvider constructor. Mongoose users should not have to use this directly
The MongooseError constructor.
The Mongoose Mixed SchemaType. Used for declaring paths in your schema that Mongoose's change tracking, casting, and validation should ignore.
const schema = new Schema({ arbitrary: mongoose.Mixed });
The Mongoose Model constructor.
The Mongoose constructor
The exports of the mongoose module is an instance of this class.
var mongoose = require('mongoose');
var mongoose2 = new mongoose.Mongoose();
The Mongoose Number SchemaType. Used for declaring paths in your schema that Mongoose should cast to numbers.
const schema = new Schema({ num: mongoose.Number });
// Equivalent to:
const schema = new Schema({ num: 'number' });
The Mongoose ObjectId SchemaType. Used for declaring paths in your schema that should be MongoDB ObjectIds. Do not use this to create a new ObjectId instance, use mongoose.Types.ObjectId
instead.
const childSchema = new Schema({ parentId: mongoose.ObjectId });
The Mongoose Promise constructor.
Storage layer for mongoose promises
The Mongoose Query constructor.
Expose connection states for user-land
The Mongoose Schema constructor
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var CatSchema = new Schema(..);
The Mongoose SchemaType constructor
The constructor used for schematype options
The various Mongoose SchemaTypes.
Alias of mongoose.Schema.Types for backwards compatibility.
The various Mongoose Types.
var mongoose = require('mongoose');
var array = mongoose.Types.Array;
Using this exposed access to the ObjectId
type, we can construct ids on demand.
var ObjectId = mongoose.Types.ObjectId;
var id1 = new ObjectId;
The Mongoose VirtualType constructor
connect()
function, except for 4 mongoose-specific options explained below. options.auth.user
. Maintained for backwards compatibility. options.auth.password
. Maintained for backwards compatibility. true
to opt in to the MongoDB driver's new URL parser logic. true
to opt in to the MongoDB driver's replica set and sharded cluster monitoring engine. true
, this connection will use createIndex()
instead of ensureIndex()
for automatic index builds via Model.init()
. false
to make findOneAndUpdate()
and findOneAndRemove()
use native findOneAndUpdate()
rather than findAndModify()
. reconnectInterval
milliseconds for reconnectTries
times, and give up afterward. When the driver gives up, the mongoose connection emits a reconnectFailed
event. This option does nothing for replica set connections. reconnectTries
option above. poolSize
is 5. Keep in mind that, as of MongoDB 3.4, MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See Slow Trains in MongoDB and Node.js. bufferCommands
to false
on your schemas if you want your database operations to fail immediately when the driver is not connected, as opposed to waiting for reconnection. socket#setTimeout()
function. 30000
by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to Node.js socket#setTimeout()
function after the MongoDB driver successfully completes. dns.lookup()
function. May be either 0,
4, or
6.
4means use IPv4 only,
6means use IPv6 only,
0` means try both. this
if connection succeeded Opens the default mongoose connection.
mongoose.connect('mongodb://user:pass@localhost:port/database');
// replica sets
var uri = 'mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/mydatabase';
mongoose.connect(uri);
// with options
mongoose.connect(uri, options);
// optional callback that gets fired when initial connection completed
var uri = 'mongodb://nonexistent.domain:27000';
mongoose.connect(uri, function(error) {
// if error is truthy, the initial connection failed.
})
The Mongoose module's default connection. Equivalent to mongoose.connections[0]
, see connections
.
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.
To create a new connection, use createConnection()
.
An array containing all connections associated with this Mongoose instance. By default, there is 1 connection. Calling createConnection()
adds a connection to this array.
const mongoose = require('mongoose');
mongoose.connections.length; // 1, just the default connection
mongoose.connections[0] === mongoose.connection; // true
mongoose.createConnection('mongodb://localhost:27017/test');
mongoose.connections.length; // 2
connect()
function, except for 4 mongoose-specific options explained below. options.auth.user
. Maintained for backwards compatibility. options.auth.password
. Maintained for backwards compatibility. true
to make all connections set the useNewUrlParser
option by default. true
to make all connections set the useUnifiedTopology
option by default. true
, this connection will use createIndex()
instead of ensureIndex()
for automatic index builds via Model.init()
. false
to make findOneAndUpdate()
and findOneAndRemove()
use native findOneAndUpdate()
rather than findAndModify()
. reconnectInterval
milliseconds for reconnectTries
times, and give up afterward. When the driver gives up, the mongoose connection emits a reconnectFailed
event. This option does nothing for replica set connections. reconnectTries
option above. poolSize
is 5. Keep in mind that, as of MongoDB 3.4, MongoDB only allows one operation per socket at a time, so you may want to increase this if you find you have a few slow queries that are blocking faster queries from proceeding. See Slow Trains in MongoDB and Node.js. bufferCommands
to false
on your schemas if you want your database operations to fail immediately when the driver is not connected, as opposed to waiting for reconnection. socket#setTimeout()
function. 30000
by default, you should set this to 2-3x your longest running operation if you expect some of your database operations to run longer than 20 seconds. This option is passed to Node.js socket#setTimeout()
function after the MongoDB driver successfully completes. dns.lookup()
function. May be either 0,
4, or
6.
4means use IPv4 only,
6means use IPv6 only,
0` means try both. await mongoose.createConnection()
Creates a Connection instance.
Each connection
instance maps to a single database. This method is helpful when mangaging multiple db connections.
Options passed take precedence over options included in connection strings.
// 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,anotherhost:port,yetanother:port/database');
// and options
var opts = { replset: { strategy: 'ping', rs_name: 'testSet' }}
db = mongoose.createConnection('mongodb://user:pass@localhost:port,anotherhost:port,yetanother:port/database', opts);
// 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.openUri('localhost', 'database', port, [opts]);
Removes the model named name
from the default connection, if it exists. You can use this function to clean up any models you created in your tests to prevent OverwriteModelErrors.
Equivalent to mongoose.connection.deleteModel(name)
.
mongoose.model('User', new Schema({ name: String }));
console.log(mongoose.model('User')); // Model object
mongoose.deleteModel('User');
console.log(mongoose.model('User')); // undefined
// Usually useful in a Mocha `afterEach()` hook
afterEach(function() {
mongoose.deleteModel(/.+/); // Delete every model
});
Runs .close()
on all connections in parallel.
The underlying driver this Mongoose instance uses to communicate with the database. A driver is a Mongoose-specific interface that defines functions like find()
.
Gets mongoose options
mongoose.get('test') // returns the 'test' value
Returns true if Mongoose can cast the given value to an ObjectId, or false otherwise.
mongoose.isValidObjectId(new mongoose.Types.ObjectId()); // true
mongoose.isValidObjectId('0123456789ab'); // true
mongoose.isValidObjectId(6); // false
name
. Mongoose will create the model if it doesn't already exist. Defines a model or retrieves it.
Models defined on the mongoose
instance are available to all connection created by the same mongoose
instance.
If you call mongoose.model()
with twice the same name but a different schema, you will get an OverwriteModelError
. If you call mongoose.model()
with the same name and same schema, you'll get the same schema back.
var mongoose = require('mongoose');
// define an Actor model with this mongoose instance
const Schema = new Schema({ name: String });
mongoose.model('Actor', schema);
// create a new connection
var conn = mongoose.createConnection(..);
// create Actor model
var Actor = conn.model('Actor', schema);
conn.model('Actor') === Actor; // true
conn.model('Actor', schema) === Actor; // true, same schema
conn.model('Actor', schema, 'actors') === Actor; // true, same schema and collection name
// This throws an `OverwriteModelError` because the schema is different.
conn.model('Actor', new Schema({ name: String }));
When no collection
argument is passed, Mongoose uses the model name. If you don't like this behavior, either pass a collection name, use mongoose.pluralize()
, or set your schemas collection name option.
var schema = new Schema({ name: String }, { collection: 'actor' });
// or
schema.set('collection', 'actor');
// or
var collectionName = 'actor'
var M = mongoose.model('Actor', schema, collectionName)
Returns an array of model names created on this instance of Mongoose.
Does not include names of models created using connection.model()
.
The node-mongodb-native driver Mongoose uses.
The mquery query builder Mongoose uses.
Mongoose uses this function to get the current time when setting timestamps. You may stub out this function using a tool like Sinon for testing.
Declares a global plugin executed on all Schemas.
Equivalent to calling .plugin(fn)
on each Schema you create.
mongoose-legacy-pluralize
. Getter/setter around function for pluralizing collection names.
Sets mongoose options
mongoose.set('test', value) // sets the 'test' option to `value`
mongoose.set('debug', true) // enable logging collection methods + arguments to the console
mongoose.set('debug', function(collectionName, methodName, arg1, arg2...) {}); // use custom function to log collection methods + arguments
true
to make Mongoose's default index build use createIndex()
instead of ensureIndex()
to avoid deprecation warnings from the MongoDB driver.false
to make findOneAndUpdate()
and findOneAndRemove()
use native findOneAndUpdate()
rather than findAndModify()
.true
to make all connections set the useNewUrlParser
option by defaulttrue
to make all connections set the useUnifiedTopology
option by defaulttrue
to clone()
all schemas before compiling into a model._id
that returns this
for convenience with populate. Set this to false to remove the getter.{ transform: true, flattenDecimals: true }
by default. Overwrites default objects to toObject()
{ transform: true, flattenDecimals: true }
by default. Overwrites default objects to toJSON()
, for determining how Mongoose documents get serialized by JSON.stringify()
false
, true
, or 'throw'
. Sets the default strict mode for schemas.populate()
to your select()
. The schema-level option selectPopulatedPaths
overwrites this one.false
or true
. Sets the default typePojoToMixed for schemas.ClientSession
Requires MongoDB >= 3.6.0. Starts a MongoDB session for benefits like causal consistency, retryable writes, and transactions.
Calling mongoose.startSession()
is equivalent to calling mongoose.connection.startSession()
. Sessions are scoped to a connection, so calling mongoose.startSession()
starts a session on the default mongoose connection.
The Mongoose version
console.log(mongoose.version); // '5.x.x'
© 2010 LearnBoost
Licensed under the MIT License.
https://mongoosejs.com/docs/api/mongoose.html