简体   繁体   English

MongoDB:如何将一个模式用作不同文件中定义的不同集合的子文档

[英]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 档案1

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

File 2 档案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 . 所以,问题是:如何在另一个文件中定义一次ParameterSchema ,并从文件1文件2中使用它。

Export the parameter sub-doc schema as a module. 将参数子doc模式导出为模块。

// 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');
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM