从MongooseModel#discriminator函数创建模型时如何设置鉴别器密钥的值?

时间:2018-01-23 22:02:14

标签: mongoose mongoose-schema

使用Mongoose我明白我可以使用鉴别器功能使用鉴别器密钥在同一个集合上生成不同的模式。

const options = { discriminatorKey: 'kind' };
const Event = mongoose.model('Event, new Schema({
 name: { type: String }
}, options);

const ClickEvent = Event.discriminator('ClickEvent', new Schema({
 url: { type: String }
}, options);

// on another file
const ClickEvent = mongoose.model('ClickEvent');
const clickEvent = new ClickEvent({
 name: 'sir',
 url: 'http://somewhere.com/hello'
});
console.log(clickEvent); // { name: 'sir', url: 'http://somewhere.com/hello', kind: 'ClickEvent' }
// look carefully kind is set to ClickEvent

我想要的是kind以某种方式设置为click。 我怎么能这样做?我希望这样的事情:

const ClickEvent = Event.discriminator('ClickEvent', new Schema({
     url: { type: String }
    }, { ...options, discriminatorValue: 'click' });

1 个答案:

答案 0 :(得分:1)

对于Mongoose 5.2+,您可以将值作为API Doc中指定的第3个参数传递

const ClickEvent = Event.discriminator('ClickEvent', new Schema({
  url: { type: String }
}), "click")

,而kind将设置为“点击”