MongoDB: How to use one schema as sub-document for different collections defined in different files

I have this Schema:

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

And I want to use it as sub-document, in two or more collections which are defined in different files like this:

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 define ParameterSchema one time only, in another file, and use it from File 1 and from File 2.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

Export the parameter sub-doc 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 i.e. 
// module.exports = mongoose.model('Parameter', ParameterSchema);

Now require the exported module schema in your parent document.

// 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 sub document.

var FirstCollection = require('./FirstCollection')

var feat = new FirstCollection({
  name: 'foo',
  parameters: [{
    id: 'bar',
    value: 'foobar'
  }]
});

feat.save(function(err) {
  console.log('Feature Saved');
})

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply