代码之家  ›  专栏  ›  技术社区  ›  Remy

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

  •  1
  • Remy  · 技术社区  · 8 年前

    有了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 回复  |  直到 8 年前
        1
  •  1
  •   Putt Potsawee    7 年前

    对于Mongoose 5.2+,可以按照 API Doc

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

    以及 kind 将设置为“单击”