当前位置: 首页 > 工具软件 > Mongoose > 使用案例 >

mongoose

袁帅
2023-12-01

概念

  • 是npm提供 的包,主要用于能够在nodejs中使用MongoDB的数据库并进行数据交互。mongoose本身提供了很多api来操作数据库,api就需要开发人员在nodejs程序中调用。

作用

  • 能够使用程序来操作MongoDB数据库

安装 mongoose

npm i mongoose

在nodejs中连接数据库 声明db.js


在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;

 类似资料: