In region.server.model.js I want to have
var RegionSchema = new Schema({
name: {type: String},
user: {type: Schema.ObjectId, ref: 'User'},
bases: [BaseSchema]
});
mongoose.model('Region', RegionSchema);
And in another file named base.server.model.js I want to have
var BaseSchema = new Schema({
name: {type: String},
region: {type: Schema.ObjectId, ref: 'Region'}
});
mongoose.model('Base', BaseSchema);
It is crashing with
bases: [BaseSchema]
^
ReferenceError: BaseSchema is not defined
I cannot figure out how in mean.js to relate or link these two files.
Thank you!
You can access a Mongoose Model's schema via Model#schema, so you can do:
// Ensure the base model is defined first.
require('./base.server.model.js');
var RegionSchema = new Schema({
name: {type: String},
user: {type: Schema.ObjectId, ref: 'User'},
bases: [mongoose.model('Base').schema]
});
mongoose.model('Region', RegionSchema);
Your model here is actually embedded, which means it is the "Schema" object and not the "model" that is being embedded into the "Region" model here. So the problem with your current multiple files is that you need to "export" that object and then "require" it in for your other module.
A typical setup is something like this, slightly abridged and just calling the file base.js:
var Schema = require('mongoose').Schema;
var BaseSchema = new Schema({
name: { type: String },
region: { type: Schema.ObjectId, ref: 'Region' }
});
module.exports = BaseSchema;
And then of course in another region.js:
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
BaseSchema = require('./base');
var RegionSchema = new Schema({
name: { type: String },
user: { type: Schema.ObjectId, ref: 'User' },
bases: [BaseSchema]
});
module.exports = mongoose.model('Region', RegionSchema);
Where you "require" by the path to where you defined the schema. Noting here that since this is "embedded" there would be no need to define a "model" for "base" here as the items are created as "sub-documents" in the same "regions" collection.
If you actually wanted a "referenced" schema with the "base" items in their own collection then you define differently:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var BaseSchema = new Schema({
name: { type: String },
region: { type: Schema.ObjectId, ref: 'Region' }
});
module.exports = mongoose.model( 'Base', BaseSchema );
And for "region":
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var RegionSchema = new Schema({
name: { type: String },
user: { type: Schema.ObjectId, ref: 'User' },
bases: [{ type: Schema.ObjectId, ref: 'Base' }]
});
module.exports = mongoose.model('Region', RegionSchema);
There is no need to "require" as the "model" is exposed to the mongoose object.
Also noting that while you "can" just access the models with mongoose.model() later, a general good practice it to "export" the model result so you can later "require" in other modules and have an object ready to work with.