[英]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.