简体   繁体   中英

Adding field to schema using mongoose in node js

I am trying to write a schema that takes the parameters required by an activity. I am want to add a field 'activityParameters' that will be case specific depending on the activityType. Suppose if the activityType is email then the activityParameters should store details like'to:String, from:String, subject: String, body: String' and if the activity is "export" then it should store parameters like 'path:String' . Different types of activity will have different parameters. Please help me how to do this.

var activity_type = {
  values: 'email export'.split(' '),
  message: 'validation failed for path `{PATH}` with value `{VALUE}`'
};
var activitySchema = new Schema({
  activityName: String,
  activityDescription: String,
  executionTime: {type: Date , default: null},
  activityStartTime: {type: Date , default: null},
  activityCompletionTime: {type: Date , default: null},
  activityType: {type:String, enum: activity_type},
  //activityParameters: ,
  appName : String,
  activityRetryCount: {type:Number,default:0},
  createdOn: {type:Date , default:Date.now},
  deletedOn: {type: Date , default: null},
  updatedOn: {type: Date , default: null}

});

There's really no good answer for doing this with mongoose and maintaining a strongly typed schema.

You can specify all the fields for each type on the schema and then use them depending on type (export vs message).

var activitySchema = new Schema({
    ...
    activityParameters: {
        to:String, 
        from:String,
        path:String
}});

You might consider having a key per subtype to be an improvement:

var activitySchema = new Schema({
    ...
   emailActivityParameters:{
      to:String, 
      from:String,
   },

  exportActivityParameters:{
      path:String, 
   }
});

It would be pretty easy to access each "subdocument" depending on the activity type.

Finally, you can have a key called activityParameters and have that be freeform json:

var activitySchema = new Schema({
    ...
    activityParameters: {}
});

In this case you can preserve your schema integrity using custom validators.

If these approaches don't appeal then maybe mongoose isn't the right tool you. You could use a lower level mongo driver and then something like Typescript or json schema to validate your models before you save them to mongoose. Check out this, for example: https://github.com/litixsoft/lx-valid .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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