• Mongoose模块


    一、Mongoose

    Mongoose是在node.js环境中对MongoDB数据库操作的封装,一种对象模型工具,可以将数据库中的数据转换为JavaScript对象供我们使用。

    1、名词解释

    Schema :
    它是一种以文件形式存储的数据库模型骨架,不具备对数据库操作的能力,仅仅只是数据库在程序片段中的一种表现,可以理解为表结构。

    Model :
    由Schema发布生成的模型,具有抽象属性和行为的数据库操作对

    Entity :
    由Model创建的实体,他的操作也会影响数据库

    2、Schema、Model、Entity的关系

    Schema生成Model,Model创造Entity,Model和Entity都可对数据库操作造成影响,但Model比Entity更具操作性。

    3、命名规范(建议)

    var PersonSchema; //Person的文本属性
    var PersonModel; //Person的数据库模型
    var PersonEntity; //Person实体

    4、实现增删改查

    4.1、安装插件

    npm install mongoose
    请添加图片描述

    4.2、引用:

    var mongoose = require(‘mongoose’);

    4.3、创建mongoconfig.js用于连接MongoDB数据库

    // 导入mongoose模块
    
    const mongoose = require('mongoose')
    
    //定义连接mogondb的字符串(链接地址)
    
    const db_url= 'mongodb://localhost:27017/mvc'
    
    //连接
    
    mongoose.connect(db_url,{useNewUrlParser:true,useUnifiedTopology:true})
    
    
    //连接成功
    
    mongoose.connection.on('connected',function (){
        console.log('MongoDB Connection open to'+db_url)
    })
    
    //连接异常
    mongoose.connection.on('error',function (err){
        console.log('MongoDB Connection Eroor:'+err)
    })
    
    //断开连接
    
    mongoose.connection.on('disconnected',function (){
        console.log('MongoDB disconnectied')
    })
    
    module.exports=mongoose
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    4.4、创建Shema(classes.js)

    var mongoose = require('../mogoconfig')
    var Schema = mongoose.Schema
    
    //定义schema
    
    var  ClassesSchema = new Schema({
        name:{type:String},
        age:{type:Number},
        sex:{type:String},
        hobby:{type:Array}
    });
    
    //由Schema生成model,model具有对数据库的操作能力
    
    module.exports = mongoose.model('Classes',ClassesSchema)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    4.5、创建路由文件

    4.6、增删改查

    (1)、增加:使用Model的实例调用save方法(使用Entity操作数据库)

    var express = require('express')
    
    const ClassesModel = require('../config/model/classes')
    
    const router = express.Router()
    //http://localhost:3000/mongo/add
    router.get('/add',(req, res) => {
        let clazz = new ClassesModel({
            name:'郭芙',
            age:22,
            sex:'女',
            hobby:['武术','绘画']
        })
        clazz.save(function (err,result){
            if(err){
                res.json({
                    code:1001,
                    msg:'插入数据失败'
                })
            }else{
                    res.json({
                        code:1002,
                        msg:'插入数据成功',
                        data:result
                    })
                }
    
        })
    })
    module.exports = router
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30

    在这里插入图片描述
    (2)、删除:使用Model操作数据库

    a、deleteOne:删除一条记录,返回删除的数量
    b、deleteMany:删除多条记录,返回删除的数量
    c、findOneAndDelete:先查找后删除,若没有找到匹配的记录不执行删除,返回null
    d、findByIdAndDelete

    var express = require('express')
    
    const ClassesModel = require('../config/model/classes')
    
    const router = express.Router()
    //http://localhost:3000/mongo/remove
    
    router.delete('/remove',(req, res) => {
        ClassesModel.deleteOne({'name':'小红'},(err,result)=>{
            if(err){
                res.json({
                    code:1001,
                    msg:'删除失败'
                })
            }else{
                res.json({
                    code:1002,
                    msg:'删除成功',
                    data:result
                })
            }
        })
    
    })
    module.exports = router
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25

    在这里插入图片描述
    删除后"小红"后的数据库:
    在这里插入图片描述

    (3)、更新:使用Model操作数据库

    a、updateOne、updateMany:返回更新的数量
    b、findOneAndUpdate、findByIdAndUpdate:先查找后更新,若没有找到匹配的记录不执行删除,返回null

    var express = require('express')
    
    const ClassesModel = require('../config/model/classes')
    
    const router = express.Router()
    //http://localhost:3000/mongo/modify
    router.put('/modify',(req, res) => {
        ClassesModel.updateOne({'name':'小王'},{'name':'王五','age':'28'},(err,result)=>{
            if(err){
                res.json({
                    code:1001,
                    msg:'更新失败'
                })
            }else{
                res.json({
                    code:1002,
                    msg:'更新成功',
                    data:result
                })
            }
        })
    })
    module.exports = router
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23

    在这里插入图片描述
    更新后数据:
    在这里插入图片描述

    (4)、查询:使用Model操作数据库

    a、find():查询所有
    b、findOne({}):按条件查询
    c、findById():按id查询

    var express = require('express')
    
    const ClassesModel = require('../config/model/classes')
    
    const router = express.Router()
    //http://localhost:3000/mongo/findAll
    router.get('/findAll',(req, res) => {
        ClassesModel.find(function(err,result){
            if(err){
                console.log(err)
                res.send({
                    code:1001,
                    msg:'查询失败'
                })
            }else{
                res.send({
                    code:1002,
                    msg:'查询成功',
                    data:result
                })
            }
        })
    })
    module.exports = router
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    在这里插入图片描述

  • 相关阅读:
    LeetCode --- 1967. Number of Strings That Appear as Substrings in Word 解题报告
    「互动有礼,感谢有你」参与互动就有机会获赠 Navicat Premium 16
    【leetcode刷题】练习Day1 1480.一维数组的动态和
    tiup mirror
    java健身俱乐部管理系统计算机毕业设计MyBatis+系统+LW文档+源码+调试部署
    阿里巴巴1688/京东/淘宝天猫API接口
    安装TPDSS
    【计算机视觉|人脸建模】学习从图像中回归3D面部形状和表情而无需3D监督
    白天建筑师,晚上CG艺术家,他将建筑的华丽发挥极致
    轮播图动态渲染
  • 原文地址:https://blog.csdn.net/thwr1881/article/details/126041571