npm i mongoose
在db.js中开头引入模块后添加以下代码:
const mongoose = require('mongoose');//引入mongoose
const dbURI = 'mongodb://127.0.0.1:3000/school'; // 其中 school 为连接的数据库名称
mongoose.connect(dbURI, {useNewUrlParser: true, useUnifiedTopology: true});
mongoose.connection.on('connected', function() {
console.log('Mongoose 已连接到 ' + dbURI);
});
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
let studentSchema = new Schema({
studentNum: {
type: String,
required: true,
index: true,
unique: true,
trim: true,
},
studentName: {
type: String,
required: true,
unique: true,
minlength: 2,
maxlength: 10,
},
tel: {
type: String,
required: true,
},
birthday: {
type: String,
},
education: {
type: String,
},
classid:{
type:Schema.Types.ObjectId,
ref:"classModel",
},
}, { versionKey: false });
//参数分别为 导出model的名字,Schema的名字,数据库collection的名字
module.exports = mongoose.model("student", studentSchema, "studentArr");
班级列表
const mongoose = require('mongoose');
const Schema = mongoose.Schema
let classSchema = new Schema({
className:{
type: String,
required: true,
minlength:2,
maxlength:10,
trim: true
},
classType:{
type: String,
required: true
},
classTeacher:{
type: String,
required: true
}
});
module.exports = mongoose.model("classModel",classSchema,"classArr")
index.js
require("./db.js");
let studentModel = require("./studentModel");
let classModel = require("./classModel");
module.exports.studentModel = studentModel;
module.exports.classModel = classModel;