zoukankan      html  css  js  c++  java
  • nodeJS中使用mongoose模块操作mongodb数据库

     在实际运用中,对于数据库的操作我们不可能一直在cmd命令行中进行操作,一般情况下需要在node环境中来操作mongodb数据库,这时就需要引入mongoose模块来对数据库进行增删改查等操作。

    首先,启动数据库服务:

      mongod --dbpath (db文件夹路径)

    然后安装mongoose模块:

      npm install mongoose -S

    app.js文件:

     1 const mongoose = require('mongoose')
     2 
     3 // 连接数据库:如果不存在指定数据库文件则会自动创建(该方法会返回一个promise对象)
     4 mongoose.connect('mongodb://localhost:27017/project',{
     5     useNewUrlParser:true,
     6     useUnifiedTopology:true
     7 }).then( async ()=>{
     8     console.log('数据库连接成功');
     9 }.catch(()=>{
    10     console.log('数据库连接失败');     
    11 })

    建模型:(代码均在.then回调函数中执行)

     1 // 先定义数据库中集合的数据格式
     2 let studentSchema = new mongoose.Schema({   // 表示数据库中集合的数据有 name sex age
     3         name:{type:String,require:true},
     4         sex:{type: String},
     5         age:{type: Number,require: true},        // require属性决定该类型数据是否必须存在集合中,为true则必须存在
     6         className:{type: String,default:'中二班'}    //default属性设置默认值
     7     })
     8 let Student =  mongoose.model("class1",studentSchema)
     9 
    10 // 简写
    11 let Student = mongoose.model('class1',new mongoose.Schema({
    12        name:String,
    13        sex:String,
    14        age:Number
    15  }))

    添加数据

     1 //向集合中插入一条数据 create函数返回的是一个 promise
     2     let result1 = await Student.create({
     3         name:'张三',
     4         sex:'男',
     5         age:20
     6     })
     7     console.log(result1);
     8 
     9 //向集合中插入多条数据
    10     Student.create([
    11         {
    12             name:'小海',
    13             sex:'男',
    14             age:21
    15         },
    16         {
    17             name:'小菲',
    18             sex:'女',
    19             age:20
    20         },
    21         {
    22             name:'小明',
    23             sex:'男',
    24             age:23
    25         }
    26     ])

    查询数据

    1 //查询集合中的数据 find函数返回的是一个 promise
    2     let result2 = await Student.find({name:'张三'})
    3     console.log(result2);

    删除数据

    1 //删除集合中的一条数据 deleteOne函数返回的也是一个promise
    2     let result3 = await Student.deleteOne({name:'张三'})
    3     console.log(result3);
    4 
    5 //删除集合中的多条数据 deleteMany函数返回一个promise
    6     let result4 = await Student.deleteMany({name:"张三"})
    7     console.log(result4);

    修改数据

    1 //更新一条集合中的数据 updateOne函数返回一个promise
    2     let result5 = await Student.updateOne({name:'小菲'},{$set:{name:'小红'}},)
    3     console.log(result5);
    4 
    5 //更新多条集合中的数据 updateMany函数返回一个promise
    6     let result6 = await Student.updateMany({name:"小菲"},{$set:{name:'菲菲'}})
    7     console.log(result6);

      

  • 相关阅读:
    连通最大子数组和(结对开发)
    第五周学习进度情况
    敏捷开发方法综述
    第四周学习进度情况
    环形数组最大子数组之和
    第四次程序(结对开发)
    第三周学习进度情况
    第三次程序—四则运算(结对开发)
    构建之法阅读笔记02
    按照Right-BICEP要求对实验二进行测试
  • 原文地址:https://www.cnblogs.com/zsp-1064239893/p/11775519.html
Copyright © 2011-2022 走看看