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 ?
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.
Mongoose is an ODM that provides a straightforward and schema-based solution to model your application data on top of MongoDB's native drivers.
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.
mongoose.model
ties the defined model to the default connection that was created by calling mongoose.connect
.db.model
ties the model to the connection that was created by calling var db = mongoose.createConnection
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With