Member-only story
Using MongoDB with Mongoose — Joins with Various Options
3 min readJan 20, 2021
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.
Removing Foreign Documents
If we remove foreign documents, then when we try to reference a linked foreign document, it’ll return null
.
For instance, if we have:
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
});
await author.save();
const story1 = new Story({
title: 'Mongoose Story',
author: author._id
});
await story1.save();
await…