Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use model.export in separate model files?

While looking at some Stackoverflow answers for questions about splitting out model data, I see two different formats. See below:

var UserSchema = mongoose.Schema({
    name: String
})

module.exports = mongoose.model('User', UserSchema);

versus this method:

var UserSchema = mongoose.Schema({
    name: String
})

mongoose.model('User', UserSchema);

What is the difference between using module.exports... versus just using mongoose.model...?

like image 582
Evan Emolo Avatar asked Mar 17 '13 15:03

Evan Emolo


1 Answers

mongoose.model returns the Model it defines. Setting it as module.exports allows you to easily create instances of the Model, without retrieving it from the connection.

a.js

var User = require('./b');
var myUser = new User;

b.js

var UserSchema = mongoose.Schema({
    name: String
})

module.exports = mongoose.model('User', UserSchema);

... note how I can directly call new User (after setting User to be require('./b')... this is what module.exports allows me to do. Note this isn't part of mongoose per-se, but of Nodes module system.

like image 116
Matt Avatar answered Nov 18 '22 19:11

Matt