简体   繁体   English

如何使用 nodejs、expressjs 将教师 id /name 推送到 mongodb 中的 studentSchema

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

I want to add favorite teachers id to student schema from list of teachers.我想从教师列表中将最喜欢的教师 ID 添加到学生模式中。 So when the student clicks the "add favorite teacher " button, that particular teacher id will save in the student schema.因此,当学生单击“添加最喜欢的老师”按钮时,该特定教师 ID 将保存在学生模式中。

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?那么将教师 ID 推送到学生模式的后端路由代码是什么?

It looks like your student schema contains an instance of your teacher schema, not just the teacherID.看起来您的学生模式包含教师模式的实例,而不仅仅是教师 ID。 If your request will contain the studentID in params, and teacherID in its body, I would do something like the following.如果您的请求将在 params 中包含 studentID,在其正文中包含teacherID,我会执行以下操作。

I'd first create two middleware functions - one to ensure your returned studentID is valid.我将首先创建两个中间件函数 - 一个确保您返回的学生 ID 有效。 Here the studentID is returned in the params via req.params.id .这里 studentID 通过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.第二个检查所选的teacherID 是否有效。 Here the teacherID is returned via the body of the request, req.body.id这里的teacherID是通过请求体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);
  }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用Node.js,Express.js从MongoDB中获取数据 - How to fetch data from mongodb using nodejs, expressjs NodeJS / ExpressJS / MongoDB简单API错误 - NodeJS/ExpressJS/MongoDB Simple API Errors 均值堆栈:如何使用nodejs expressjs和angular 6在mongodb中存储图像? - Mean Stack: How can I store image in mongodb with nodejs expressjs and angular 6? 如何使用Web Speech API使用ExpressJS和Node.js在mongodb中插入其数据 - how to use web speech api to insert its data in mongodb using ExpressJS and nodejs 如何使用 REACTJS、NODEJS、EXPRESSJS 和 MONGODB 中的 API 进行 POST 数据? - How can do POST data using API from REACTJS ,NODEJS,EXPRESSJS AND MONGODB? 如何在作为教师模式一部分的 MongoDB 中为时间表创建模式? - How can I create a schema for timetables in MongoDB that is part of a Teacher Schema? 仅当满足 mongoDB 中的条件时,如何将值推送到数组字段?(Nodejs) - How to push a value to an array field only if it meets a condition in mongoDB?(Nodejs) NodeJS expressJS上载穆特尔和护照,并将文件保存到MongoDB - NodeJS expressJS upload and save file to MongoDB with multer and passport (Nodejs, expressjs, mongodb) UnhandledPromiseRejectionWarning: TypeError: 无法读取未定义的属性“用户名” - (Nodejs, expressjs, mongodb) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'username' of undefined expressJS:如何在获取呼叫时推送socketIO? - expressJS: How to push socketIO on get call?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM