簡體   English   中英

如何使用nodejs和mongoDB插入一對一、一對多的關系

[英]How insert one-to-one, one-to-many relationship using nodejs with mongoDB

我的數據庫中有兩個集合,它們如下

  1. 學生
  2. 課程

我想插入數據就像one-to-oneone-to-many關系。

例子

在我的form-data發送以下form-data

  1. 姓名
  2. 電子郵件
  3. 電話
  4. 密碼
  5. 課程名
  6. course_cost

以上數據的nameemailphonepassword存儲在學生表中。

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表,但我不知道如何添加一個一對一的關系

我認為首先您需要重新設計架構。 考慮到您有兩個不同的學生和課程集合,您需要學生中的課程參考和課程集合中的學生參考。 這將幫助您執行以下類型的查詢。

  1. 獲取學生 x 的課程列表。
  2. 獲取已注冊課程 ABC 的學生列表。 在學生模式中添加課程數組,在課程模式中添加學生數組。 看看這個

在您的路線中,您要求姓名、電子郵件、電話、密碼。 然后你嘗試插入 course_name, course_cost。 您需要在課程集合中插入 student_id

這是一個老問題,但是,我相信很多人可能正在尋找這種類似模式關系設計的解決方案。 您需要在模型中聲明一對多模式關系。

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM