node.js - 如何使用nodejs和mongoDB插入一对一、一对多的关系
问题描述
我的数据库中有两个集合,它们如下
- 学生
- 课程
我想插入数据之类one-to-one
的one-to-many
关系。
例子
我发送了以下数据form-data
- 姓名
- 电子邮件
- 电话
- 密码
- 课程名
- course_cost
上述数据的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
推荐阅读
- c++ - CMake 构建错误:未定义对“deflateEnd”的引用
- sql - 查询以获取每个类别中至少出现 3 次的每个样本
- ruby-on-rails - Heroku:在推送到 Heroku 期间,无法在 MacOS 上的 Rails 6 中通过 Bundler 安装 gem
- sql - Oracle SQL - 将行显示为列 - 多对多关系
- python - 名称未定义。用ex48艰难学python
- azure - 具有公共 IP 的应用程序网关后面的 Azure 容器组
- mysql - docker节点随机开始给操作超时
- android - 等级构建编译给出依赖错误
- python - 将反向数据从一个 csv 文件写入另一个文件的问题
- shell - 是否可以在没有密码的情况下为远程 Linux 系统执行 netstat?