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.
Use the $push operator to add a sub-document. Let us first create a collection with documents − Following is the query to display all documents from a collection with the help of find () method − This will produce the following output −
While MongoDB certainly supports references from one document to another, and even multi-document joins, it’s a mistake to use a document database the same way you use a relational one. For example, let’s look at a simple structure with a user, and their addresses.
MongoDB also lets you enforce a schema to validate your data and maintain a data structure. We will use MongoDB Atlas and MongoDB Compass to demonstrate how.
Embedded documents are an efficient and clean way to store related data, especially data that’s regularly accessed together. In general, when designing schemas for MongoDB, you should prefer embedding by default, and use references and application-side or database-side joins only when they’re worthwhile.
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');
})
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