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