如何在MongoDB / Mongoose中动态添加架构

时间:2018-10-17 02:22:08

标签: node.js mongodb mongoose mongoose-schema

我想创建一个由用户定义的数据库,每个用户可以拥有自己的数据库风格。所以我使用了strict: false,但是现在的问题是我无法让用户定义模型下每个模式的type

示例

const mongoose = require('mongoose');

const testSchema = new mongoose.Schema({
    label: {
        required: 'please enter label',
        trim: true,
        type: String
    },
    url: {
        type: String,
        trim: true,
    },
    settings: {}  //User defined 
    }, {
        timestamps: true, strict: false
    });


module.exports = mongoose.model('test', testSchema);

在上述情况下,我希望该设置由用户定义

{
    "label": "About Us",
    "url": "www.google.com",
    "settings": { 
        "name": {
            "type": "String",   //Problem is Here, i can't send datatype directly
            "required": true
            },
        "age": {
            "type": "Number",
            "required": true,
            "enum": [10, 12]
        }
    }
}

所以请告诉我,我如何让用户定义架构的类型?

3 个答案:

答案 0 :(得分:2)

strict: true并不意味着您可以将任何内容传递到settings字段。

这意味着您的架构格式是动态的-您可能在文档中使用未在架构中定义的意外字段名称。


回答您的问题:

好像您想要子文档,让我们创建另一个模式并将其附加为类型:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const types = Schema.Types;

const testSettingsSchema = new Schema({
  name: {
    type: types.String,
    required: true
  },
  age: {
    type: types.Number,
    required: true
    enum: [10, 12]
  }
},
{
  _id : false,
  timestamps: false, 
  strict: false
});

const testSchema = new Schema({
  label: {
    required: 'please enter label',
    trim: true,
    type: types.String
  },
  url: {
    type: types.String,
    trim: true,
  },
  settings: {
    type: testSettingsSchema,
    required: true
  }
}, 
{
  timestamps: true, 
  strict: true
});


module.exports = mongoose.model('test', testSchema);



但是要获得更大的灵活性并避免创建大的test文档(因为用户可能会推送不可预测的大对象),请创建另一个架构:testSettings指向test_settings集合并进行{{ 1}}字段供参考:

settings

创建为:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const types = Schema.Types;

const testSettingsSchema = new Schema({
  name: {
    type: types.Mixed
  },
  age: {
    type: types.Mixed
  }
},
{
  collection: 'test_settings',
  timestamps: false, 
  strict: false // tells to mongoose that schema may "grow"
});
mongoose.model('testSettings', testSettingsSchema);

const testSchema = new Schema({
  label: {
    required: 'please enter label',
    trim: true,
    type: types.String
  },
  url: {
    type: types.String,
    trim: true,
  },
  settings: {
    type: types.ObjectId,
    ref: 'testSettings'
    default: null
  }
}, 
{
  collection: 'tests',
  timestamps: true, 
  strict: true
});


module.exports = mongoose.model('test', testSchema);

,并在请求时间获得为:

const Test = mongoose.model('test');
const TestSettings = mongoose.model('testSettings');

app.post('/tests', async (req, res) => {
  try {
    const testSettings = await TestSettings.create(req.body.settings);

    const test = new Test(req.body);
    test.settings = testSettings._id;
    await test.save();

    res.status(201).send({_id: test._id});
  }
  catch(error) {
    res.status(500).send({message: error.message});
  }
});

答案 1 :(得分:0)

将您的设置字段定义为 Schema.Types.Mixed ,因此您可以在其中设置任何类型的字段,例如Number , String , Array , Date , Boolean ..etc

const mongoose = require('mongoose');

const testSchema = new mongoose.Schema({
    label: {
        required: 'please enter label',
        trim: true,
        type: String
    },
    url: {
        type: String,
        trim: true,
    },
    settings: {
      type:Schema.Types.Mixed ,
      default: {}
    } 
    }, {
        timestamps: true, strict: false
    });


module.exports = mongoose.model('test', testSchema);

保存文档时:

app.post('/save',function(req,res){
    var setting = {};
    setting.age= req.body.age;
    setting.name= req.body.name;

   var test = new Test({
       test.label: req.body.label;
       test.url :req.body.url;
       test.setting: setting
    });
  test.save(function(err){
     if(err) {return res.json(err);}
     else{ res.json({status:'success',message:'saved.'});}
   });

});

答案 2 :(得分:0)

只要有人遇到NestJS和schemaFactory的问题,这就是我解决的方法:

...

@Schema({ strict: false })
export class Content {}

@Schema()
export class Deadletter extends Document {
  @Prop({type: Header})
  header: Header;,

  @Prop({type: Metadata})
  _metadata?: Metadata;
  
  @Prop({type: Content})
  content: any;    
}

export const deadLetterFullSchema = SchemaFactory.createForClass(Deadletter);