Connection constructor
For practical reasons, a Connection equals a Db.
Closes the connection
Retrieves a collection, creating it if not cached.
Not typically needed by applications. Just talk to your collection through your model.
A hash of the collections associated with this connection
A hash of the global options that are associated with this connection
Helper for createCollection()
. Will explicitly create the given collection with specified options. Used to create capped collections and views from mongoose.
Options are passed down without modification to the MongoDB driver's createCollection()
function
The mongodb.Db instance, set when the connection is opened
Removes the model named name
from this connection, if it exists. You can use this function to clean up any models you created in your tests to prevent OverwriteModelErrors.
conn.model('User', new Schema({ name: String }));
console.log(conn.model('User')); // Model object
conn.deleteModel('User');
console.log(conn.model('User')); // undefined
// Usually useful in a Mocha `afterEach()` hook
afterEach(function() {
conn.deleteModel(/.+/); // Delete every model
});
Helper for dropCollection()
. Will delete the given collection, including all documents and indexes.
Helper for dropDatabase()
. Deletes the given database, including all collections, documents, and indexes.
const conn = mongoose.createConnection('mongodb://localhost:27017/mydb');
// Deletes the entire 'mydb' database
await conn.dropDatabase();
Gets the value of the option key
. Equivalent to conn.options[key]
conn.get('test'); // returns the 'test' value
The host name portion of the URI. If multiple hosts, such as a replica set, this will contain the first host name in the URI
mongoose.createConnection('mongodb://localhost:27017/mydb').host; // "localhost"
Defines or retrieves a 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.
var schema = new Schema({ name: String }, { collection: 'actor' });
// or
schema.set('collection', 'actor');
// or
var collectionName = 'actor'
var M = conn.model('Actor', schema, collectionName)
Returns an array of model names created on this connection.
A POJO containing a map from model names to models. Contains all models that have been added to this connection using Connection#model()
.
const conn = mongoose.createConnection();
const Test = conn.model('Test', mongoose.Schema({ name: String }));
Object.keys(conn.models).length; // 1
conn.models.Test === Test; // true
The name of the database this connection points to.
mongoose.createConnection('mongodb://localhost:27017/mydb').name; // "mydb"
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. Opens the connection with a URI using MongoClient.connect()
.
The password specified in the URI
mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').pass; // "psw"
Declares a plugin executed on all schemas you pass to conn.model()
Equivalent to calling .plugin(fn)
on each schema you create.
const db = mongoose.createConnection('mongodb://localhost:27017/mydb');
db.plugin(() => console.log('Applied'));
db.plugins.length; // 1
db.model('Test', new Schema({})); // Prints "Applied"
The plugins that will be applied to all models created on this connection.
const db = mongoose.createConnection('mongodb://localhost:27017/mydb');
db.plugin(() => console.log('Applied'));
db.plugins.length; // 1
db.model('Test', new Schema({})); // Prints "Applied"
The port portion of the URI. If multiple hosts, such as a replica set, this will contain the port from the first host name in the URI.
mongoose.createConnection('mongodb://localhost:27017/mydb').port; // 27017
Connection ready state
Each state change emits its associated event name.
conn.on('connected', callback);
conn.on('disconnected', callback);
Sets the value of the option key
. Equivalent to conn.options[key] = val
maxTimeMS
: Set maxTimeMS
for all queries on this connection.useFindAndModify
: Set to false
to work around the findAndModify()
deprecation warning
conn.set('test', 'foo');
conn.get('test'); // 'foo'
conn.options.test; // 'foo'
ClientSession
Requires MongoDB >= 3.6.0. Starts a MongoDB session for benefits like causal consistency, retryable writes, and transactions.
const session = await conn.startSession();
let doc = await Person.findOne({ name: 'Ned Stark' }, null, { session });
await doc.remove();
// `doc` will always be null, even if reading from a replica set
// secondary. Without causal consistency, it is possible to
// get a doc back from the below query if the query reads from a
// secondary that is experiencing replication lag.
doc = await Person.findOne({ name: 'Ned Stark' }, null, { session, readPreference: 'secondary' });
useDb()
multiple times with the same name only creates 1 connection object. Switches to a different database using the same connection pool.
Returns a new connection object, with the new db.
The username specified in the URI
mongoose.createConnection('mongodb://val:psw@localhost:27017/mydb').user; // "val"
© 2010 LearnBoost
Licensed under the MIT License.
https://mongoosejs.com/docs/api/connection.html