To make MongoDB database manipulation easy, we can use the Mongoose NPM package to make working with MongoDB databases easier.
In this article, we’ll look at how to use Mongoose to manipulate our MongoDB database.
Discriminators are a schema inheritance mechanism.
They let us enable multiple models to have overlapping schemas on top of the same MongoDB collection.
For example, we can use them as follows:
async function run() {
const { createConnection, Types, Schema } = require('mongoose');
const db = createConnection('mongodb://localhost:27017/test');
const options = { discriminatorKey: 'kind' };
const eventSchema = new Schema({ time: Date }, options);
const Event = db.model('Event', eventSchema);
const ClickedLinkEvent = Event.discriminator('ClickedLink',
new Schema({ url: String }, options));
const genericEvent = new Event({ time: Date.now(), url: 'mongodb.com' });
console.log(genericEvent)
const clickedEvent =
new ClickedLinkEvent({ time: Date.now(), url: 'mongodb.com' });
console.log(clickedEvent)
}
run();
We created an Event
model from the eventSchema
.
It has the discriminatorKey
so that we get can discriminate between the 2 documents we create later.
To create the ClickedLinkEvent
model, we call Event.discriminator
to create a model by inheriting from the Event
schema.
We add the url
field to the ClickedLinkEvent
model.
Then when we add the url
to the Event
document and the ClickedLinkEvent
document, only the clickedEvent
object has the url
property.
#javascript #technology #programming