From 771e9bd0d4dff5c87bbe3f7ad4433afb5b9be5cb Mon Sep 17 00:00:00 2001 From: JayWll Date: Wed, 15 Jul 2020 16:46:50 -0600 Subject: [PATCH] Video 114: The User/Task Relationship --- task-manager/src/index.js | 15 +++++++++++++++ task-manager/src/models/task.js | 5 +++++ task-manager/src/models/user.js | 6 ++++++ task-manager/src/routers/task.js | 8 ++++++-- 4 files changed, 32 insertions(+), 2 deletions(-) diff --git a/task-manager/src/index.js b/task-manager/src/index.js index a6a6465..720a61a 100644 --- a/task-manager/src/index.js +++ b/task-manager/src/index.js @@ -25,3 +25,18 @@ app.use(taskRouter) app.listen(port, () => { console.log('Server is up on port ' + port) }) + +const Task = require('./models/task') +const User = require('./models/user') + +const main = async () => { + // const task = await Task.findById('5f0f845f55f3ad018f2305fc') + // await task.populate('owner').execPopulate() + // console.log(task.owner) + + const user = await User.findById('5f0f838e040ee20177d799f3') + await user.populate('tasks').execPopulate() + console.log(user.tasks) +} + +main() diff --git a/task-manager/src/models/task.js b/task-manager/src/models/task.js index e1b56a1..f87dfe4 100644 --- a/task-manager/src/models/task.js +++ b/task-manager/src/models/task.js @@ -9,6 +9,11 @@ const Task = mongoose.model('Task', { completed: { type: Boolean, default: false + }, + owner: { + type: mongoose.Schema.Types.ObjectId, + required: true, + ref: 'User' } }) diff --git a/task-manager/src/models/user.js b/task-manager/src/models/user.js index 452be95..fd56e6c 100644 --- a/task-manager/src/models/user.js +++ b/task-manager/src/models/user.js @@ -49,6 +49,12 @@ const userSchema = new mongoose.Schema({ }] }) +userSchema.virtual('tasks', { + ref: 'Task', + localField: '_id', + foreignField: 'owner' +}) + userSchema.methods.toJSON = function() { const user = this const userObject = user.toObject() diff --git a/task-manager/src/routers/task.js b/task-manager/src/routers/task.js index 3fa3871..d8f3896 100644 --- a/task-manager/src/routers/task.js +++ b/task-manager/src/routers/task.js @@ -1,9 +1,13 @@ const express = require('express') const Task = require('../models/task') +const auth = require('../middleware/auth') const router = new express.Router() -router.post('/tasks', async (req, res) => { - const task = new Task(req.body) +router.post('/tasks', auth, async (req, res) => { + const task = new Task({ + ...req.body, + owner: req.user._id + }) try { await task.save()