【问题标题】:How insert one-to-one, one-to-many relationship using nodejs with mongoDB如何使用nodejs和mongoDB插入一对一、一对多的关系
【发布时间】:2019-03-07 11:50:37
【问题描述】:

我的数据库中有两个如下的集合

  1. 学生
  2. 课程

我想插入类似one-to-oneone-to-many 关系的数据。

示例

我在我的form-data 中发送了以下数据

  1. 姓名
  2. 电子邮件
  3. 电话
  4. 密码
  5. 课程名称
  6. 课程费用

上述数据的nameemailphonepassword存储在student表中。

course_namecourse_coststudent_id 一起存储到course 表中。

这是我的代码:

route/students.js

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


const router = express.Router();

let Student = require('../models/student_model');

router.post('/add_student', function(req, res){
    let data = new Student();
    data.name = req.body.name;
    data.email = req.body.email;
    data.phone = req.body.phone;
    data.password = req.body.password;

    data.save(function(err, data){
        if(err) throw err;
        res.send(data);
    });

});

module.exports = router;

models/student_model.js

const mongoose = require('mongoose');

let StudentSchema =  mongoose.Schema({
    name:{
        type: String
    },
    email:{
        type: String
    },
    phone:{
        type: String
    },
    password:{
        type: String
    },

    }, { collection: 'student' });


const Student = module.exports = mongoose.model('Student', StudentSchema);

这是我的 API 调用:

我上面的代码已经完成了存储在student表中的学生数据,但是我不知道如何添加一对一的关系

【问题讨论】:

  • 你有course 架构吗?

标签: node.js mongodb insert foreign-keys relationship


【解决方案1】:

我认为首先您需要重新设计架构。考虑到学生和课程有两个不同的集合,您需要学生中的课程参考和课程集合中的学生参考。这将帮助您执行以下类型的查询。

  1. 获取学生 x 的课程列表。
  2. 获取已注册 ABC 课程的学生列表。 在学生模式中添加课程数组,在课程模式中添加学生数组。 签出this

【讨论】:

    【解决方案2】:

    在您的路线中,您需要姓名、电子邮件、电话、密码。然后你尝试插入 course_name, course_cost。您需要在课程集合中插入 student_id

    【讨论】:

      【解决方案3】:

      这是一个老问题,但是,我相信很多人可能正在寻找这种类似模式关系设计的解决方案。您需要在模型中声明一对多模式关系。

      const StudentSchema = new Schema({
          name: String,
          email: String,
          phone: String,
          password: String,
          course: [courseSchema] //this will be the relationship
      })
      const CourseSchema = new Schema({
          course_name: String, 
          course_cost: String
      })
      
      const Student = mongoose.model('student', StudentSchema)
      
      module.export = Student;
      

      【讨论】:

        猜你喜欢
        • 2021-07-30
        • 2017-02-12
        • 1970-01-01
        • 1970-01-01
        • 2015-10-25
        • 1970-01-01
        • 1970-01-01
        • 2014-10-18
        • 1970-01-01
        相关资源
        最近更新 更多