Skip to content

Instantly share code, notes, and snippets.

@cziem
Created August 17, 2019 12:48
Show Gist options
  • Select an option

  • Save cziem/5bcdecc5a238c83f9182f113d7ff4957 to your computer and use it in GitHub Desktop.

Select an option

Save cziem/5bcdecc5a238c83f9182f113d7ff4957 to your computer and use it in GitHub Desktop.
contrived example of working with mongoose populate
const { Post, Author } = require('./models/post.schema')
const { Poem, User } = require('./models/poem.schema')
// Then for the post, you can run a mongoose populate like so...
const getPosts = async (req, res) => await Post.find({}).populate('author')
// Then for the poem, you want to run a mongoose populate like so...
const getPoems = async (req, res) => await Poem.find({}).populate({
path: 'author',
model: 'User'
})
module.exports = {
getPosts,
getPoems
}
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// If you had a Peom schema like this
const poemSchema = new Schema({
title: String,
body: String,
author: {
type: Schema.Types.ObjectId,
ref: 'User'
}
}, { timestamp: true })
const Poem = mongoose.model('Poem', poemSchema)
// And a User schema like so...
const userSchema = new Schema({
name: String,
username: String,
password: String,
post: [
{
type: Schema.Types.ObjectId,
ref: 'Post'
}
]
}, { timestamp: true })
const User = mongoose.model('User', userSchema)
module.exports = { Poem, User }
/*
* How to work with mongoose populate
*/
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// Here's your Post schema
const postSchema = new Schema({
title: String,
body: String,
author: {
type: Schema.Types.ObjectId,
ref: 'Author'
}
}, { timestamp: true })
const Post = mongoose.model('Post', postSchema)
// Here's your Author schema
const authorSchema = new Schema({
name: String,
username: String,
password: String,
post: [
{
type: Schema.Types.ObjectId,
ref: 'Post'
}
]
}, { timestamp: true })
const Author = mongoose.model('Author', authorSchema)
module.exports = { Post, Author }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment