Skip to content

Instantly share code, notes, and snippets.

@heytulsiprasad
Created February 25, 2020 06:42
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 heytulsiprasad/57e1d6aa3aabe0530be45bf386a1aca3 to your computer and use it in GitHub Desktop.
Save heytulsiprasad/57e1d6aa3aabe0530be45bf386a1aca3 to your computer and use it in GitHub Desktop.
making relation to another mongo document using mongoose methods
// this is a file in the root folder
const User = require("./models/user.js");
const main = async () => {
// to show tasks saved by a particular user
const user = await User.findById("5e54b46f3022d70b2ceaf2e5")
// console.log(user.tasks) --> without virtual (returns undefined, as tasks ain't a field)
user.populate("tasks").execPopulate()
console.log(user.tasks) // returns all tasks
}
main()
// this is the user model root >> models >> user.js
const mongoose = require("mongoose")
const userSchema = new mongoose.Schema({
email: {
type: String,
required: true
},
password: {
type: String,
required: true
}
})
userSchema.virtual("tasks", {
ref: "User",
localField: "_id",
foreignField: "owner"
})
const User = new mongoose.model("User", userSchema)
module.exports = User
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment