如果db中存在新的项目,Keystone JS将禁止创建新项目。

问题描述 投票:0回答:1

我使用的是keystone js,我有session feild,其中包含day和stage应该是唯一的。

    keystone.createList('Stage', {
  fields: {
    name: {
      type: Text
    }
  }
});
keystone.createList('Day', {
  labelResolver: day => day.day,
  fields: {
    day: {
      label: 'Session Day',
      type: CalendarDay,
      format: 'Do MMMM YYYY',
      defaultValue: Date.now()
    }
  },
  schemaDoc: 'Session Day Date'
});
keystone.createList('Session', {
  labelResolver: () => 'Session',

  fields: {
    day: {
      type: Relationship,
      ref: 'Day',
      isRequired: true,
      isUnique: true,

    },
    stage: {
      type: Relationship,
      ref: 'Stage',
      many: false,
      isRequired: true,
      isUnique: true,
      hooks: {
        beforeChange: async () => { 

         },
      }
    }
  }

});

Sessions day & stage应该是唯一的,如果我创建了一次,就不应该再创建。

例如,如果我有{day: 2020-03-09, stage: Venture}我不应该再创建相同的日期& 阶段,因为它们已经存在于数据库中。

但我可以创建{day: 2020-03-09, stage: Miracle}。奇迹}。

javascript mongodb keystonejs
1个回答
0
投票

如果你使用mongodb作为后端,你可以使用adapterConfig来实现这一点。

keystone.createList('MyList', {
  fields: {
    // other fields 
    day: { /* ... config */},
    stage: { /* ... config */},
  },
  adapterConfig: {
    configureMongooseSchema: (schema) => {
      try {
        schema.index({ day: 1, stage: 1 }, { unique: 1 });
      } catch (error) {
        console.log(error);
      }
    }
  },
});
© www.soinside.com 2019 - 2024. All rights reserved.