1
0

Video 114: The User/Task Relationship

This commit is contained in:
JayWll 2020-07-15 16:46:50 -06:00
parent b06a1d3e88
commit 771e9bd0d4
4 changed files with 32 additions and 2 deletions

View File

@ -25,3 +25,18 @@ app.use(taskRouter)
app.listen(port, () => { app.listen(port, () => {
console.log('Server is up on port ' + 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()

View File

@ -9,6 +9,11 @@ const Task = mongoose.model('Task', {
completed: { completed: {
type: Boolean, type: Boolean,
default: false default: false
},
owner: {
type: mongoose.Schema.Types.ObjectId,
required: true,
ref: 'User'
} }
}) })

View File

@ -49,6 +49,12 @@ const userSchema = new mongoose.Schema({
}] }]
}) })
userSchema.virtual('tasks', {
ref: 'Task',
localField: '_id',
foreignField: 'owner'
})
userSchema.methods.toJSON = function() { userSchema.methods.toJSON = function() {
const user = this const user = this
const userObject = user.toObject() const userObject = user.toObject()

View File

@ -1,9 +1,13 @@
const express = require('express') const express = require('express')
const Task = require('../models/task') const Task = require('../models/task')
const auth = require('../middleware/auth')
const router = new express.Router() const router = new express.Router()
router.post('/tasks', async (req, res) => { router.post('/tasks', auth, async (req, res) => {
const task = new Task(req.body) const task = new Task({
...req.body,
owner: req.user._id
})
try { try {
await task.save() await task.save()