I'm defining my application models and i have separate files for each model that i'm defining, my question is, i need to create a model that use a sub-document, but that's on another file, how can i use that Schema on my model ? what i mean is that all examples i've seen declare the Child model and the Parent on the same file, example:
var childSchema = new Schema({ name: 'string' }); var parentSchema = new Schema({ children: [childSchema] });
I have one file called user.js
that defines the user model :
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var userSchema = new Schema({ _id : Schema.Types.ObjectId, username : String, }); module.exports = mongoose.model( 'User', userSchema );
And on another file called sport.js
i have the other model definition for the sports:
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var sportSchema = new Schema({ _id : Schema.Types.ObjectId, name : String }); module.exports = mongoose.model( 'Sport', sportSchema );
So on my user model I need to define a field for the sports that the user will follow, but i do not know how to define that sub-document since the sports definition is on another file, I tried this:
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var SportsModel = require('sport'); var userSchema = new Schema({ _id : Schema.Types.ObjectId, username : String, sports : [SportsModel] }); module.exports = mongoose.model( 'User', userSchema );
But i'm not sure if that's the correct way since what i'm exporting is the model, not the Schema.
Thanks in advance, i want to define each model on separate files to maintain order.
In Mongoose, subdocuments are documents that are nested in other documents. You can spot a subdocument when a schema is nested in another schema. Note: MongoDB calls subdocuments embedded documents.
Subdocuments are documents embedded in other documents. In Mongoose, this means you can nest schemas in other schemas. Mongoose has two distinct notions of subdocuments: arrays of subdocuments and single nested subdocuments.
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.
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.
You can access a Model's schema via its schema
property. So this should work:
var userSchema = new Schema({ _id : Schema.Types.ObjectId, username : String, sports : [SportsModel.schema] });
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