Mongoose.model vs Connection.model vs Model.model Mongoose.model vs Connection.model vs Model.model mongoose mongoose

Mongoose.model vs Connection.model vs Model.model


  1. mongoose.model ties the defined model to the default connection that was created by calling mongoose.connect.
  2. db.model ties the model to the connection that was created by calling var db = mongoose.createConnection.
  3. doc.model looks up another model by name using the connection that doc's model is tied to.

All three can be sensibly used in the same program; which one to use just depends on the situation.


ok here is what I found

Important! If you opened a separate connection using mongoose.createConnection() but attempt to access the model through mongoose.model('ModelName') it will not work as expected since it is not hooked up to an active db connection. In this case access your model through the connection you created:

var conn = mongoose.createConnection('your connection string');var MyModel = conn.model('ModelName', schema);var m = new MyModel;m.save() // works

vs

var conn = mongoose.createConnection('your connection string');var MyModel = mongoose.model('ModelName', schema);var m = new MyModel;m.save() // does not work b/c the default connection object was never connected


mongoose.connect is for you connect to same database,although your database is balance or replicaSet

db.model is for multiple connections open to Mongo, each with different read/write settings