I have two collections in my database those are following
I want to insert data's like one-to-one
, one-to-many
relationship.
example
Am sent following data's in my form-data
The above data's name
, email
, phone
, password
stored in student table.
And course_name
, course_cost
stored to course table with 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);
My above code am done store student data stored in
student
table, but i don't know how to add one-to-one relationship
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. You need to insert student_id in course collection
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;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.