首页 > 解决方案 > 如何使用nodejs和mongoDB插入一对一、一对多的关系

问题描述

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

  1. 学生
  2. 课程

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

例子

我发送了以下数据form-data

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

上述数据的name, email, phone,password存储在学生表中。

并且course_namecourse_cost存储到课程表中student_id

这是我的代码:

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表中的学生数据,但我不知道如何添加一对一的关系

标签: node.jsmongodbinsertforeign-keysrelationship

解决方案


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


推荐阅读