鉴别器

model.discriminator() 函数

鉴别器是一种模式继承机制。它们使您能够在同一个基础 MongoDB 集合上拥有多个具有重叠模式的模型。

假设您想在一个集合中跟踪不同类型的事件。每个事件都将有时间戳,但代表点击链接的事件应该有一个 URL。您可以使用 model.discriminator() 函数来实现这一点。该函数接受 3 个参数,一个模型名称、一个鉴别器模式和一个可选键(默认为模型名称)。它返回一个模型,该模型的模式是基本模式和鉴别器模式的并集。

const options = { discriminatorKey: 'kind' };

const eventSchema = new mongoose.Schema({ time: Date }, options);
const Event = mongoose.model('Event', eventSchema);

// ClickedLinkEvent is a special type of Event that has
// a URL.
const ClickedLinkEvent = Event.discriminator('ClickedLink',
  new mongoose.Schema({ url: String }, options));

// When you create a generic event, it can't have a URL field...
const genericEvent = new Event({ time: Date.now(), url: 'google.com' });
assert.ok(!genericEvent.url);

// But a ClickedLinkEvent can
const clickedEvent = new ClickedLinkEvent({ time: Date.now(), url: 'google.com' });
assert.ok(clickedEvent.url);

鉴别器保存到事件模型的集合中

假设您创建了另一个鉴别器来跟踪新用户注册的事件。这些 SignedUpEvent 实例将存储在与通用事件和 ClickedLinkEvent 实例相同的集合中。

const event1 = new Event({ time: Date.now() });
const event2 = new ClickedLinkEvent({ time: Date.now(), url: 'google.com' });
const event3 = new SignedUpEvent({ time: Date.now(), user: 'testuser' });


await Promise.all([event1.save(), event2.save(), event3.save()]);
const count = await Event.countDocuments();
assert.equal(count, 3);

鉴别器键

Mongoose 区分不同鉴别器模型的方式是通过 '鉴别器键',默认情况下为 __t。Mongoose 向您的模式添加了一个名为 __t 的字符串路径,它用于跟踪此文档是哪个鉴别器的实例。

const event1 = new Event({ time: Date.now() });
const event2 = new ClickedLinkEvent({ time: Date.now(), url: 'google.com' });
const event3 = new SignedUpEvent({ time: Date.now(), user: 'testuser' });

assert.ok(!event1.__t);
assert.equal(event2.__t, 'ClickedLink');
assert.equal(event3.__t, 'SignedUp');

更新鉴别器键

默认情况下,Mongoose 不允许您更新鉴别器键。save() 在您尝试更新鉴别器键时会抛出错误。而 findOneAndUpdate()updateOne() 等会删除鉴别器键更新。

let event = new ClickedLinkEvent({ time: Date.now(), url: 'google.com' });
await event.save();

event.__t = 'SignedUp';
// ValidationError: ClickedLink validation failed: __t: Cast to String failed for value "SignedUp" (type string) at path "__t"
  await event.save();

event = await ClickedLinkEvent.findByIdAndUpdate(event._id, { __t: 'SignedUp' }, { new: true });
event.__t; // 'ClickedLink', update was a no-op

要更新文档的鉴别器键,请使用 findOneAndUpdate()updateOne(),并将 overwriteDiscriminatorKey 选项设置为如下所示。

let event = new ClickedLinkEvent({ time: Date.now(), url: 'google.com' });
await event.save();

event = await ClickedLinkEvent.findByIdAndUpdate(
  event._id,
  { __t: 'SignedUp' },
  { overwriteDiscriminatorKey: true, new: true }
);
event.__t; // 'SignedUp', updated discriminator key

数组中的嵌入式鉴别器

您还可以在嵌入式文档数组上定义鉴别器。嵌入式鉴别器与众不同,因为不同的鉴别器类型存储在同一个文档数组中(在一个文档内),而不是同一个集合中。换句话说,嵌入式鉴别器允许您将匹配不同模式的子文档存储在同一个数组中。

作为一个通用的最佳实践,请确保您在使用模式之前在模式上声明任何钩子。您不应在调用 discriminator() 后调用 pre()post()

const eventSchema = new Schema({ message: String },
  { discriminatorKey: 'kind', _id: false });

const batchSchema = new Schema({ events: [eventSchema] });

// `batchSchema.path('events')` gets the mongoose `DocumentArray`
// For TypeScript, use `schema.path<Schema.Types.DocumentArray>('events')`
const docArray = batchSchema.path('events');

// The `events` array can contain 2 different types of events, a
// 'clicked' event that requires an element id that was clicked...
const clickedSchema = new Schema({
  element: {
    type: String,
    required: true
  }
}, { _id: false });
// Make sure to attach any hooks to `eventSchema` and `clickedSchema`
// **before** calling `discriminator()`.
const Clicked = docArray.discriminator('Clicked', clickedSchema);

// ... and a 'purchased' event that requires the product that was purchased.
const Purchased = docArray.discriminator('Purchased', new Schema({
  product: {
    type: String,
    required: true
  }
}, { _id: false }));

const Batch = db.model('EventBatch', batchSchema);

// Create a new batch of events with different kinds
const doc = await Batch.create({
  events: [
    { kind: 'Clicked', element: '#hero', message: 'hello' },
    { kind: 'Purchased', product: 'action-figure-1', message: 'world' }
  ]
});

assert.equal(doc.events.length, 2);

assert.equal(doc.events[0].element, '#hero');
assert.equal(doc.events[0].message, 'hello');
assert.ok(doc.events[0] instanceof Clicked);

assert.equal(doc.events[1].product, 'action-figure-1');
assert.equal(doc.events[1].message, 'world');
assert.ok(doc.events[1] instanceof Purchased);

doc.events.push({ kind: 'Purchased', product: 'action-figure-2' });

await doc.save();

assert.equal(doc.events.length, 3);

assert.equal(doc.events[2].product, 'action-figure-2');
assert.ok(doc.events[2] instanceof Purchased);

单级嵌套鉴别器

您还可以在单个嵌套子文档上定义鉴别器,类似于您在子文档数组上定义鉴别器的方式。

作为一个通用的最佳实践,请确保您在使用模式之前在模式上声明任何钩子。您不应在调用 discriminator() 后调用 pre()post()

const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' });
const schema = Schema({ shape: shapeSchema });

// For TypeScript, use `schema.path<Schema.Types.Subdocument>('shape').discriminator(...)`
schema.path('shape').discriminator('Circle', Schema({ radius: String }));
schema.path('shape').discriminator('Square', Schema({ side: Number }));

const MyModel = mongoose.model('ShapeTest', schema);

// If `kind` is set to 'Circle', then `shape` will have a `radius` property
let doc = new MyModel({ shape: { kind: 'Circle', radius: 5 } });
doc.shape.radius; // 5

// If `kind` is set to 'Square', then `shape` will have a `side` property
doc = new MyModel({ shape: { kind: 'Square', side: 10 } });
doc.shape.side; // 10