How to push teacher id /name to studentSchema in mongodb with nodejs ,expressjs

Viewed 17

I want to add favorite teachers id to student schema from list of teachers. So when the student clicks the "add favorite teacher " button, that particular teacher id will save in the student schema.

Here is my student schema

    const mongoose = require ('mongoose')
    const studentSchema=new mongoose.Schema({
    name:{type:String,required:true}, 
    email:{type:String,required:true}, 
    phone:{type:String,required:true}, 
    password:{type:String,required:true},
    teacher : [{type : mongoose.Schema.Types.ObjectID , ref:'teachers'}],
       
})

const studentModel = mongoose.model('students',studentSchema)
module.exports=studentModel

Here is my teacher Schema

const mongoose = require ('mongoose')

    const teacherSchema=new mongoose.Schema({
        name:{type:String,required:true}, 
        email:{type:String,required:true}, 
        phone:{type:String,required:true}, 
        password:{type:String,required:true}, 
    })
    
    const teacherModel = mongoose.model('teachers',teacherSchema)
    module.exports=teacherModel

So what will be the backend route code to push the teacher id to Student schemas ?

1 Answers

It looks like your student schema contains an instance of your teacher schema, not just the teacherID. If your request will contain the studentID in params, and teacherID in its body, I would do something like the following.

I'd first create two middleware functions - one to ensure your returned studentID is valid. Here the studentID is returned in the params via req.params.id.

import { studentModel } from "./models/student.js";


// middleware - check that student id exists
async function checkStudentIdExists(req, res, next) {
  let item;
  try {
    item = await studentModel.findById(req.params.id);
    if (item == null) {
      return res.status(404).json({ message: "cannot find student by given id" });
    }
  } catch (err) {
    return res.status(500).json({ message: err.message });
  }
  res.student = item;
  next();
}

and the second to check that the chosen teacherID is valid. Here the teacherID is returned via the body of the request, req.body.id

import { teacherModel } from "./models/teacher.js";

// check that teacher id exists
async function checkTeacherIdExists(req, res, next) {
  let item;
  try {
    const item = await teacherModel.findById(req.body.id);
    if (item == null) {
      return res.status(404).json({ message: "cannot find teacher by given id" });
    }
  } catch (err) {
    return res.status(500).json({ message: err.message });
  }
  res.teacher = item;
  next();
}

In constructing the required route, use both middleware in a route, like this:

router.patch("/student/favoredTeacher/:id", checkStudentIdExists, checkTeacherIdExists, async (req, res) => {
  try { 
    await res.student.updateOne({teacher: res.teacher})
  } catch (err) {
    res.status(500).json(err.message);
  }
});
Related