[英]How insert one-to-one, one-to-many relationship using nodejs with mongoDB
I have two collections in my database those are following我的数据库中有两个集合,它们如下
I want to insert data's like one-to-one
, one-to-many
relationship.我想插入数据就像
one-to-one
、 one-to-many
关系。
example例子
Am sent following data's in my form-data
在我的
form-data
发送以下form-data
The above data's name
, email
, phone
, password
stored in student table.以上数据的
name
、 email
、 phone
、 password
存储在学生表中。
And course_name
, course_cost
stored to course table with student_id
.和
course_name
, course_cost
存储到带有student_id
课程表中。
This is my code:这是我的代码:
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);
This is my API call:这是我的 API 调用:
My above code am done store student data stored in
student
table, but i don't know how to add one-to-one relationship我上面的代码是存储在完成结束学生数据
student
表,但我不知道如何添加一个一对一的关系
I think first you need to redesign the schema.我认为首先您需要重新设计架构。 Considering you have two different collections for student and course, you need a reference of course in student and student reference in course collection.
考虑到您有两个不同的学生和课程集合,您需要学生中的课程参考和课程集合中的学生参考。 This will help you to execute following kind of queries.
这将帮助您执行以下类型的查询。
In your route you request name, email, phone, password.在您的路线中,您要求姓名、电子邮件、电话、密码。 Then you try insert course_name, course_cost.
然后你尝试插入 course_name, course_cost。 You need to insert student_id in course collection
您需要在课程集合中插入 student_id
This is an old question, however, i believe many people may be looking for a solution to this similar schema relation design.这是一个老问题,但是,我相信很多人可能正在寻找这种类似模式关系设计的解决方案。 You need to declare a One to Many schema relation in your Model.
您需要在模型中声明一对多模式关系。
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.