Reputation: 57
I've noticed that certain libraries like
Mockgoose (https://github.com/mccormicka/Mockgoose/blob/master/test/index.spec.js)
use require('mongoose').Mongoose to declare an instance of mongoose like this:
var Mongoose = require('mongoose').Mongoose;
var mongoose = new Mongoose();
var db = mongoose.connect('mongodb://localhost:27017/TestingDB');
However, most examples I've seen online does this to connect to a database:
var mongoose = require('mongoose');
var db = mongoose.connect('mongodb://localhost:27017/TestingDB');
I just want to know if there's a difference between these two methods of getting an instance of mongoose or are they really two different ways to get the same thing.
Thanks
Upvotes: 3
Views: 555
Reputation: 95048
There is a difference between the two.
require('mongoose')
returns an instance of Mongoose
, and new require('mongoose').Mongoose
gives you a new instance of Mongoose
that isn't the same instance as the one returned from require('mongoose')
. The latter is useful when a particular part of your app needs it's own instance of mongoose that doesn't conflict with the rest (which makes it perfect for unit testing)
In a typical application though you'll want to simply use require('mongoose')
so that everywhere you use require('mongoose')
, you'll get the same instance.
https://github.com/Automattic/mongoose/blob/master/lib/index.js#L520
Upvotes: 4