0

I've been trying to add new data to the education part of my database using this method

Controller

newUserEdu: async (req, res, next) => {
        const user = await User.findById(req.value.body.user)

        const newEdu = req.value.body;
        delete newEdu.user;

        const edu = new Edu(newEdu);
        edu.users = user;

        await edu.save();

        user.education.push(edu);
        await user.save();

        res.status(200).json(edu);

    },

deleteEdu: async(req, res, next) => {
        const { eduId } = req.value.params;

        const edu = await Edu.findById(eduId);
        if( !edu ){
            return res.status(404).json({error: 'Field Non-Existent'});
        }

        const userID = edu.users;

        const user = await User.findById(userID);

        await edu.remove();

        user.education.pull(edu);
        await user.save();

        res.status(200).json({success: true});
    }

The models of the respective user and the education are the following

User Model

 username: String,
    password: String,
    name: String,
    gender: String,
    dob: Date,
    email: String,
    contact: String,
    education: [{
        type:Schema.Types.ObjectId,
        ref:'edu'
    }]

Education Model

const eduSchema = new Schema({
    institute: String,
    program: String,
    start: Number,
    end: Number,
    field: String,
    users: {
        type: Schema.Types.ObjectId,
        ref: 'user'
    }
});

Postman gives out this error which alludes to the line containing push()

TypeError: Cannot read property 'education' of null
    at newUserWrk (G:\Learning\University\Web Tech-II\Projects\scala2\NodeJS\controllers\wrk.controller.js:20:14)
  • `user` is only defined after the `await User.findById()` but before that it's `undefined`. So if you placed that line with `push()` within a condition e.g. `if (!user) {...}`, you should be good. Let me know. – MwamiTovi May 31 '20 at 01:46
  • I tried checking with the console.log() to see if the parameters are being passed and they are but it's not being assigned to const user = await User.findById(req.value.body.user) – Shayaan Varzgani May 31 '20 at 02:10
  • Then try using `let` instead of `const` statement – MwamiTovi May 31 '20 at 04:51

0 Answers0