Discriminator is a model inheritance mechanism that can define different structures in the same collecton. For example, if our business has two entities customer and Order, it would be normal to create two models:
-
The customer model
const Customer = mongoose.model('Customer'.new mongoose.Schema({ firstName: { type: String }, lastName: { type: String }, email: { type: String}}))Copy the code
-
Order model
const Order = mongoose.model('Order'.new mongoose.Schema({ orderDate: { type: Date.default: Date.now }, items: [String]}))Copy the code
Then write data using:
-
Create a customer
const customer = new Customer({ firstName: "John".lastName: "Doe".email: "[email protected]" }) customer.save((err, savedCustomer) = > console.log(JSON.stringify(savedCustomer))) Copy the code
-
Create the order
const order = new Order({ items: ["apple"."orange"."pear"] }) order.save((err, savedOrder) = > console.log(JSON.stringify(savedOrder))) Copy the code
There is now one data item in the customer collection and one data item in the order collection.
With discriminator, however, you can put two completely unrelated models in the same table. For example, we create a Base model with the collection name data and specify the discriminatorKey as __type (if not, The default is __t) :
const baseOptions = { discriminatorKey: '__type'.collection: 'data' }
const Base = mongoose.model('Base'.new mongoose.Schema({}, baseOptions))
Copy the code
We can then have both Customer and Order inherit from the Base model:
const Customer = Base.discriminator('Customer'.new mongoose.Schema({
firstName: { type: String },
lastName: { type: String },
email: { type: String}}))const Order = Base.discriminator('Order'.new mongoose.Schema({
orderDate: { type: Date.default: Date.now },
items: [String]}))Copy the code
The code changes are minimal, and we can still use the Customer and Order models to create or query data, but we end up in the data set, where each piece of data has a __type field that distinguishes types, in this case Customer and Order.
So what’s the advantage of that? In the case of the above example, it is not appropriate to put together, unless you are buying a cloud database by the number of collections charged, otherwise it is better to put together two tables, semantic and easy to query. However, in some cases, collections of similar fields can be combined, especially if the fields of a table are dynamic. You might choose to use Mixed (which is as powerful as any in TypeScript but does not infer the specific type), but discriminator is probably a better choice.