MongoDB: how to use one schema as a subdocument for different collections defined in different files

I have this circuit:

var ParameterSchema = new Schema({ id: { type: String, trim: true, default: '' }, value: { type: String, trim: true, default: '' } }); 

And I want to use it as a sub-document in two or more collections that are defined in different files, such as:

File 1

 var FirstCollectionSchema = new Schema({ name: { type: String, trim: true, default: '' }, parameters: [ParameterSchema] }); 

File 2

 var SecondCollectionSchema = new Schema({ description: { type: String, trim: true, default: '' }, parameters: [ParameterSchema] }); 

so the question is: how can I determine ParameterSchema only once in another file and use it from File 1 and from File 2 .

+6
source share
1 answer

Export the sub-doc parameter schema as a module.

 // Parameter Model file 'Parameter.js' var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ParameterSchema = new Schema({ id: { type: String, trim: true, default: '' }, value: { type: String, trim: true, default: '' } }); module.exports = ParameterSchema; // Not as a mongoose model ie // module.exports = mongoose.model('Parameter', ParameterSchema); 

Now the exported module schema in the parent document is required.

 // Require the model exported in the Parameter.js file var mongoose = require('mongoose'); var Schema = mongoose.Schema; var Parameter = require('./Parameter'); var FirstCollectionSchema = new Schema({ name: { type: String, trim: true, default: ' }, parameters: [Parameter] }); module.exports = mongoose.model('FirstCollection', FirstCollectionSchema); 

Now you save the collection and supporting document.

 var FirstCollection = require('./FirstCollection') var feat = new FirstCollection({ name: 'foo', parameters: [{ id: 'bar', value: 'foobar' }] }); feat.save(function(err) { console.log('Feature Saved'); }) 
+12
source

Source: https://habr.com/ru/post/970584/


All Articles