Member-only story

Using MongoDB with Mongoose — Nested Documents

John Au-Yeung
3 min readJan 17, 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.

Modify Nested Documents

We can modify nested documents by accessing the path and then set the value for it.

For example, we can write:

async function run() {
const mongoose = require('mongoose');
const connection = mongoose.createConnection('mongodb://localhost:27017/test');
const childSchema = new mongoose.Schema({ name: 'string' });
const parentSchema = new mongoose.Schema({
children: [childSchema],
child: childSchema
});
const Child = await connection.model('Child', childSchema);
const Parent = await connection.model('Parent', parentSchema);
const parent = new Parent({ children: [{ name: 'Matt' }, { name: 'Sarah' }] })
await parent.save();
parent.children[0].name = 'Mary';
await parent.save();
console.log(parent);
}
run();

We get the children subarray’s first entry’s name property and set it to 'Mary' .

Then we call save on the parent to save everything.

--

--

No responses yet