• 12 【操作mongodb数据库】


    12 【操作mongodb数据库

    1.简介

    • 1.Mongoose是一个让我们可以通过Node来操作MongoDB的模块。
    • 2.Mongoose是一个对象文档模型(ODM)库,它对Node原生的MongoDB模块进行了进一步的优化封装,并提供了更多的功能。在大多数情况下,它被用来把结构化的模式应用到一个MongoDB集合,并提供了验证和类型转换等好处
    • 3.mongoose中的对象:
      • Schema 模式对象(Schema对象定义约束了数据库中的文档结构)
      • Model 模型对象(Model对象作为集合中的所有文档的表示,相当于MongoDB数据库中的集合collection)
      • Document 文档对象(Document表示集合中的具体文档,相当于集合中的一个具体的文档)

    mongoose的好处

    1. 可以为文档创建一个模式结构(Schema)
    2. 可以对模型中的对象/文档进行验证
    3. 数据可以通过类型转换转换为对象模型
    4. 可以使用中间件来应用业务逻辑挂钩
    5. 比Node原生的MongoDB驱动更容易

    安装

    npm i -S mongoose
    
    • 1

    2.连接数据库

    config/db.config.js

    // 1.引入mongoose
    const mongoose = require("mongoose");
    
    // 2.连接mongodb数据库
    // 指定连接数据库后不需要存在,当你插入第一条数据库后会自动创建数据库
    /*
    mongoose.connect('mongodb://数据库地址:端口号/数据库名',{useMongoClient:true})
    如果端口号是默认端口号(27017)则可以省略不写
    */
    mongoose.connect("mongodb://localhost:27017/ds2", {
       
        useNewUrlParser: true,
        useUnifiedTopology: true,
    });
    
    // 3.监听mongodb数据库的连接状态
    // 绑定数据库连接成功事件
    mongoose.connection.once("open", function () {
       
        console.log("连接成功");
    });
    // 绑定数据库连接失败事件
    mongoose.connection.once("close", function () {
       
        console.log("数据库连接已经断开");
    });
    
    // 4.断开数据库连接(一般不用)
    mongooes.disconnect();
    
    • 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

    注:MongoDB数据库,一般情况下,只需要连接一次,连接一次后,除非项目停止服务器关闭,否则连接一般不会断开

    在bin目录下的www文件中使用直接require(“…/config/db.config.js”)进行数据库连接的启动

    image-20221103204502381

    3.创建模式对象和模型对象

    数据库中的 Schema,为数据库对象的集合。schema 是 mongoose 里会用到的一种数据模式,可以理解为表结构的定义;每个 schema会映射到 mongodb 中的一个 collection,它不具备操作数据库的能力。

    • 每个 schema 都会映射到一个 MongoDB collection 并定义这个collection里的文档结构
    • 支持的字段类型
    类型 作用
    String 定义字符串
    Number 定义数字
    Date 定义日期
    Buffer 定义二进制
    Boolean 定义布尔值
    Mixed 定义混合类型
    ObjectId 定义对象ID
    Array 定义数组

    model/UserModel.js

    const mongoose = require("mongoose")
    const Schema=mongooes.Schema;
    //创建模式对象
    const UserType=new Schema({
       
        name:{
       
               type: 'string',
               //添加约束,保证数据的完整性,让数据按规矩统一
               require: true
            },
        age:Number,
        gender:{
       
            type:String,
            // 默认值
            default:'female'
        },
        address:String
    })
    
    //创建模型对象
    //通过Schema来创建Model
    //Model代表的是数据库中的集合,通过Model才能对数据库进行操作
    //mongoose.model(modelName,schema)
    //建立映射关系,students是集合,mongoose会自动将集合变成复数比如student会变成students
    //大写也会被自动转换为小写,比如Users会变成users
    const UserModel=mongoose.model("UserModel",UserType,"user"); 
    //第一个参数表示创建的集合的名称,第二个参数表示利用的模式对象,第三个参数是强行指定集合名称
    
    module.exports  = UserModel 
    
    • 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.1 save()

    • 操作的是文档

    案例:

    var mongoose = require('mongoose')
    const UserModel = require('../model/UserModel');
    
    //链式调用 通过new 一个Model创建一个 document
    new UserModel({
       name:"小明",age:18}).save((err,docs) => {
       
        if(!err){
       
            console.log(docs)
            res.send({
       
              code: 200,
              data: {
       
                id: docs._id,
              },
            })
            //{ _id: 6017bd1cf4cc8544d8ed2a8a, name: '小明', age: 18, __v: 0 }
        }
    })   
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21

    4.2 create()

    • 操作模型

    • Model.create(doc(s), [callback])

    • 参数:

      [doc(s)]:文档对象或文档对象数组

      [callback]:回调函数

    var mongoose = require('mongoose')
    const UserModel = require('../model/UserModel');
    
    UserModel.create({
       name:"小明",age:18},{
       name:"小红",age:10},(err,doc1,doc2) => {
       
       if(!err){
       
            console.log(doc1)
            //{ _id: 6017be2d77c8dd01242624bb, name: '小明', age: 18, __v: 0 }
            console.log(doc2)
            //{ _id: 6017be2d77c8dd01242624bc, name: '小红', age: 10, __v: 0 }
        }
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    其它:

    //Model.createOne(doc, [callback]);		创建一个对象
    //Model.createMany(doc, [callback]);		创建多个对象
    //	-doc是需要插入的文档
    //	-callback(err) 是回调函数,可以用来提示是否创建成功了
    
    • 1
    • 2
    • 3
    • 4

    4.3 insertMany()

    • Model.insertMany(doc(s), [options], [callback])
    • 返回值为一个数组
    • 案例:
    UserModel.insertMany({
       name:"小明",age:18},{
       name:"小芳",age:14},(err,docs) => {
       
       if(!err){
       
            console.log(docs)
            /*[{ _id: 6017befb5c36d64d08b72576, name: '小明', grades: 68, __v: 0 },
               { _id: 6017befb5c36d64d08b72577, name: '小芳', grades: 94, __v: 0 }]*/
        }
    })
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    5.文档查询

    _id name grades __v
    6017befb5c36d64d08b72576 小明 68 0
    6017befb5c36d64d08b72577 小芳 94 0
    6017c455ba09d355a49ec8eb 小红 52 0
    6017c455ba09d355a49ec8ec 小刚 46 0

    5.1 find()

    • Model.find(conditions, [projection], [options], [callback])

    • 参数

    ​ conditions:查询条件

    ​ [projection]:控制返回字段

    ​ [options]:配置查询参数

    ​ [callback]:回调函数–function(err,docs){}

    • 案例:

      var mongoose = require('mongoose')
      mongoose.connect('mongodb://localhost:27017/student',(err) => {
           
          if(!err){
           
              var schema = new mongoose.Schema({
           name:String,grades:Number})
              var stuModel = mongoose.model('grades',schema)
              //查询所有数据
              stuModel.find((err,docs) => {
           
                 if(!err){
           
                  	console.log(docs)
              	}
              })        
             /* [{ _id: 6017befb5c36d64d08b72576, name: '小明', grades: 68, __v: 0 },
                 { _id: 6017befb5c36d64d08b72577, name: '小芳', grades: 94, __v: 0 },
                 { _id: 6017c455ba09d355a49ec8eb, name: '小红', grades: 52, __v: 0 },
                 { _id: 6017c455ba09d355a49ec8ec, name: '小刚', grades: 46, __v: 0 }]*/
              
              //查询成绩大于60以上的数据
              stuModel.find({
           grades:{
           $gte:60}},(err,docs) => {
           
                  if(!err){
           
                       console.log(docs)
                   }
               })
              /*[{ _id: 6017befb5c36d64d08b72576, name: '小明', grades: 68, __v: 0 },
                 { _id: 6017befb5c36d64d08b72577, name: '小芳', grades: 94, __v: 0 }]*/
              
              //查询成绩大于60以上且名字里存在‘芳’的数据
              stuModel.find({
           name://,grades:{
           $gte:60}},(err,docs) => {
           
                  if(!err
      • 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
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
  • 相关阅读:
    如何使用 Xshell 连接 Linux 服务器
    使用protobuf解析Onnx文件
    24点游戏题库算法分析
    并发、并行、同步、异步、阻塞、非阻塞
    实现深度理解函数指针
    数据结构作业
    Twitter 审核研究联盟 - 深入了解 Twitter 上对话的安全性和完整性。
    Vue.js 修饰符:精准控制组件行为
    Python中直接赋值、浅拷贝和深拷贝的区别
    天地图key申请-加载地图空白问题
  • 原文地址:https://blog.csdn.net/DSelegent/article/details/128130063