Created
February 25, 2020 06:42
-
-
Save heytulsiprasad/57e1d6aa3aabe0530be45bf386a1aca3 to your computer and use it in GitHub Desktop.
making relation to another mongo document using mongoose methods
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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