Consider a very simple Express 4 app structure:
-- app.js
-- models
|--db.js
|--news.js
where news.js
contains a mongoose schema and a model based on that schema:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var newsSchema = new Schema({
title: String,
subtitle: String,
// other fields...
});
var News = mongoose.model('News', newsSchema);
To my understanding, in order for app.js
to use the News
model, it has to require the file within the script like this: require('./models/news')
. Also, news.js
would have to export the model like this: module.exports = News;
.
However, I have come across a number of scripts that do not export models (or anything for that matter) defined in a separate file while still be able to use those models and/or schema in a different file just by requiring the model file and then do something like this:
var mongoose = require('mongoose');
var News = mongoose.model('News');
How is this behavior possible? It is a special feature of Mongoose? How can a file use a model or schema defined in another file if that model/schema is not exported within that file?
Mongoose Schema vs. Model. A Mongoose model is a wrapper on the Mongoose schema. A Mongoose schema defines the structure of the document, default values, validators, etc., whereas a Mongoose model provides an interface to the database for creating, querying, updating, deleting records, etc.
Hooks for Custom Statics Statics are Mongoose's implementation of OOP static functions. You add a static function to your schema, and Mongoose attaches it to any model you compile with that schema. Mongoose 5.5 introduces the ability to add hooks for custom statics, like schema. pre('findByName') .
create() is a shortcut for saving one or more documents to the database. MyModel. create(docs) does new MyModel(doc). save() for every doc in docs.
Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.
This ultimately works because when you call require('mongoose')
in various files, you get back the same object. In other words: it gets shared between app.js
and news.js
, in your case.
When you create a new model (using mongoose.Model('Name', schema)
), Mongoose stores that model instance in an internal list of models.
This also allows you to get an instance by name, using mongoose.Model('Name')
. Mongoose will look up that model in its internal list, and return it.
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