Member-only story

Using MongoDB with Mongoose — Populate

John Au-Yeung
4 min readJan 20, 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.

Populate

We can use the populate method to join 2 models together.

For example, we can write:

async function run() {
const { createConnection, Types, Schema } = require('mongoose');
const connection = createConnection('mongodb://localhost:27017/test');
const personSchema = Schema({
_id: Schema.Types.ObjectId,
name: String,
age: Number,
stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
const storySchema = Schema({
author: { type: Schema.Types.ObjectId, ref: 'Person' },
title: String,
fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});
const Story = connection.model('Story', storySchema);
const Person = connection.model('Person', personSchema);
const author = new Person({
_id: new Types.ObjectId(),
name: 'James Smith',
age: 50
});
author.save(function (err) {
if (err) return handleError(err);
const story1 = new Story({
title: 'Mongoose Story',
author: author._id…

--

--

No responses yet