Skip to content

Instantly share code, notes, and snippets.

@dave-continuum-media
Last active October 14, 2019 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dave-continuum-media/09848138ae86508d891c65bddc537b20 to your computer and use it in GitHub Desktop.
Save dave-continuum-media/09848138ae86508d891c65bddc537b20 to your computer and use it in GitHub Desktop.
Mongoose .populated
const mongoose = require('mongoose');
mongoose.set('debug', true);
const GITHUB_ISSUE = `gh8247`;
const connectionString = `mongodb://localhost:27017/${ GITHUB_ISSUE }`;
const { Schema } = mongoose;
run().then(() => console.log('done')).catch(error => console.error(error.stack));
async function run() {
await mongoose.connect(connectionString, { useNewUrlParser: true });
await mongoose.connection.dropDatabase();
const authorSchema = new Schema({
name: { type: String, required: true },
})
const subSchema = new Schema({
author: { type: Schema.Types.ObjectId, ref: 'Author', required: true },
comment: { type: String, required: true },
});
const pageSchema = new Schema({
title: { type: String, required: true },
comments: { type: [subSchema], default: [], required: true },
});
const Author = mongoose.model('Author', authorSchema);
const Page = mongoose.model('Page', pageSchema);
const authorBob = await Author.create({ name: 'Bob Boberton' });
const authorJane = await Author.create({ name: 'Jane Janerton' });
const newPage = await Page.create({ title: 'This is a page' });
newPage.comments.push({ author: authorBob, comment: 'Hello from Bob' });
await newPage.save();
const page = await Page.findOne().populate('comments.author');
console.log(`Page comment authors populated("comments.author"): ${page.populated('comments.author')}`);
console.log(page.comments[0].toObject());
page.comments.push({ author: authorJane._id, comment: 'Hello from Jane' });
console.log('--- Pushed in a comment from Jane ---');
console.log(`Page comments length: ${page.comments.length}`);
console.log('Page comment authors populated("comments.author"):', page.populated('comments.author'));
page.comments.forEach((comment, index) => {
console.log(`page.comments[${index}].populated('author') === ${page.comments[index].populated('author')}`);
});
await page.save();
const pagePopulated = await Page.findOne().populate('comments.author');
console.log(pagePopulated.populated('comments.author'));
const pageUnpopulated = await Page.findOne();
console.log(pageUnpopulated.populated('comments.author'));
mongoose.connection.close();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment