[英]How insert one-to-one, one-to-many relationship using nodejs with mongoDB
我的數據庫中有兩個集合,它們如下
我想插入數據就像one-to-one
、 one-to-many
關系。
例子
在我的form-data
發送以下form-data
以上數據的name
、 email
、 phone
、 password
存儲在學生表中。
和course_name
, course_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);
我上面的代碼是存儲在完成結束學生數據
student
表,但我不知道如何添加一個一對一的關系
我認為首先您需要重新設計架構。 考慮到您有兩個不同的學生和課程集合,您需要學生中的課程參考和課程集合中的學生參考。 這將幫助您執行以下類型的查詢。
在您的路線中,您要求姓名、電子郵件、電話、密碼。 然后你嘗試插入 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.