Member-only story

Using MongoDB with Mongoose — Nested Document Discriminators and Plugins

John Au-Yeung
2 min readJan 21, 2021

--

Photo by Dušan Smetana on Unsplash

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 and Single Nested Documents

We can define discriminators on single nested documents.

For instance, we can write:

async function run() {
const { createConnection, Types, Schema } = require('mongoose');
const db = createConnection('mongodb://localhost:27017/test');
const shapeSchema = Schema({ name: String }, { discriminatorKey: 'kind' });
const schema = Schema({ shape: shapeSchema });
schema.path('shape').discriminator('Circle', Schema({ radius: String }));
schema.path('shape').discriminator('Square', Schema({ side: Number }));
const Model = db.model('Model', schema);
const doc = new Model({ shape: { kind: 'Circle', radius: 5 } });
console.log(doc)
}
run();

We call discriminator on the shape property with:

schema.path('shape').discriminator('Circle', Schema({ radius: String }));
schema.path('shape').discriminator('Square', Schema({ side: Number }));

--

--

No responses yet