17

I am bit confused with usage of models in mongoosejs

Models can be created using mongoose in these ways

Using Mongoose

var mongoose = require('mongoose');
var Actor = mongoose.model('Actor', new Schema({ name: String }));

Using Connection

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');

Using existing Model instance

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

Now what is the difference between model returned by Mongoose.model , Connection.model and Model.model. and when to use what , what is the recommended way to create/fetch model ?

Prashant Bhate
  • 10,907
  • 7
  • 47
  • 82

3 Answers3

23
  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.

JohnnyHK
  • 305,182
  • 66
  • 621
  • 471
16

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
Prashant Bhate
  • 10,907
  • 7
  • 47
  • 82
0

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

lixun
  • 1