Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose.model vs Connection.model vs Model.model

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 ?

like image 789
Prashant Bhate Avatar asked Oct 09 '12 18:10

Prashant Bhate


People also ask

What is the difference between Mongoose connect and Mongoose createConnection?

My understanding on the official documentation is that generally when there is only one connection mongoose. connect() is use, whereas if there is multiple instance of connection mongoose. createConnection() is used.

Is Mongoose ODM or ORM?

Mongoose is an ODM that provides a straightforward and schema-based solution to model your application data on top of MongoDB's native drivers.

What is the use of Mongoose model?

Mongoose acts as a front end to MongoDB, an open source NoSQL database that uses a document-oriented data model. A "collection" of "documents" in a MongoDB database is analogous to a "table" of "rows" in a relational database.


1 Answers

  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.

like image 63
JohnnyHK Avatar answered Sep 29 '22 14:09

JohnnyHK