References with Mongoosis

Asked

Viewed 73 times

0

I currently have 3 Collections in my project, and I need 2 of them ("Course" and "Lesson"), have a link, I want when adding a "Lesson" it to be inserted in a "Course" through a push, but is giving this error:

(Node:16156) Unhandledpromiserejectionwarning: Typeerror: Cannot read Property 'push' of Undefined

my code so yes, can anyone help me? I’m starting now with nodejs

app js.

const express = require('express');
const path = require('path');
const logger = require('morgan');
require('./config/database');
const cors = require('cors')

const usersRouter = require('./app/routes/users');
const courseRouter = require('./app/routes/courses');
const lessonRouter = require('./app/routes/lessons');

const app = express();

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(express.static(path.join(__dirname, 'public')));
app.use(cors());


app.use('/users', usersRouter);
app.use('/courses', courseRouter);
app.use('/courses', lessonRouter.courseDependent);

module.exports = app;

models/Course

const mongoose = require('mongoose');

let courseSchema = new mongoose.Schema({
    title: {type: String, text: true},
    body: {type: String, text: true},
    lessons: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Lesson'
    }],
    authorU: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'User',
        required: true
    },
    created_at: { type: Date, default: Date.now },
    updated_at: { type: Date, default: Date.now }
})

module.exports = mongoose.model('Course', courseSchema);

models/Lesson

const mongoose = require('mongoose');

let lessonSchema = new mongoose.Schema({
    title: {type: String, text: true},
    body: {type: String, text: true},
    lessons: {type: String, required: true, text: true},
    courseRef: {
        type: mongoose.Schema.Types.ObjectId,
        ref: 'Course',
        required: true
    },
    created_at: { type: Date, default: Date.now },
    updated_at: { type: Date, default: Date.now }
})

module.exports = mongoose.model('Lesson', lessonSchema);

Routes/lessons.js

const express = require('express');
const courseDependentRoute = express.Router();
const WithAuth = require('../middlewares/auth');
 
const Lesson = require('../models/lesson');
const Course = require('../models/course');

courseDependentRoute.get('/:id/lessons/new', async(req, res) => {
    try {
         let lesson = Lesson();
         res.status(200).json({courseRef: req.params.id, lesson: lesson})
    } catch (error) {
        res.status(500).json({error: 'Problemas para criar nova aula'})
    }
})

courseDependentRoute.post('/:id/newLesson', WithAuth, async(req, res) => {
    const { title, body, lessons } = req.body;
    let lesson = new Lesson({ title: title, body: body, lessons: lessons, courseRef: req.params.id })

    // try {
        await lesson.save();
        let course = await Course.findById(req.params.id);
        course.lesson.push(lesson);
        await course.save();
        res.status(200).json(course);
    // } catch (error) {
    //     res.status(500).json({error: 'Problemas para criar novo curso'})
    // }
});

module.exports = { courseDependent: courseDependentRoute };
  • 1

    See that course.lesson should be an array to be able to do the push. The mistake says he’s Undefined, so check if course has this attribute lesson

  • Really, it was that much thank you, lack of attention to my

1 answer

1


Solution

  • Change, in the file models/course, the Schema attribute of lessons for lesson or
  • Change the error line to course.lessons.push(lesson)

With an attentive reading to error, you can see that it indicates that course.lesson is undefined and therefore a push (unique method for Arrays).

In this sense, what causes this return undefined is the fact that the definition imposes the attribute in the plural lessons instead of lesson without the "s".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.