mongodb数据库及数据分页

7次阅读

共计 3807 个字符,预计需要花费 10 分钟才能阅读完成。

在做自己的一个小项目时,新学习了 mongodb 非关系型数据库,使用了 mongoose 封装好的查询方法,包括数据库分页用到的 limit 和 skip 方法,这里记录下。

1. mongodb 数据库连接

  • 参照官网文档对应的参数如下:
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
  • 使用 mongoose 进行数据库的连接
const dataBaseUrl = config.admin.username
  ? `mongodb://${config.admin.username}:${config.admin.pwd}@${config.host}/share-resource`
  : `mongodb://${config.host}/share-resource`;
mongoose.connect(dataBaseUrl, { useNewUrlParser: true});
  • 若出现警告信息:要求使用新的编译方式,则在连接的时候加上 useNewUrlParser: true

DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version.
To use the new parser, pass option {useNewUrlParser: true} to MongoClient.connect.

mongoose.connect(dataBaseUrl, { useNewUrlParser: true});
  • 在连接数据库时,对连接操作进行监听处理
mongoose.connection.on('connected', function() {console.log('Mongoose connection open to' + dataBaseUrl);
});
/* 连接数据库异常 */
mongoose.connection.on('error', function(err) {console.log('Mongoose connection error:' + err);
});
/* 连接数据库断开 */
mongoose.connection.on('disconnected', function() {console.log('Mongoose connection disconnected');
});

2. 数据类型 (mongoose 中提供的 schemaTypes)

  • 数据类型有:String,Number,Date,Buffer,Boolean,ObjectId,Array,Mixed,Map,Decimal128
  • 在数据库直接用 insert 方法进行数据插入时,若不强制指定数字的类型,则默认是插入 double 型数字

3. mongoose 对数据库操作的方法

3.1 数据的插入

  • 先要新建 schema 文件
const mongoose = require('../database/mongodbHelper');
const Message= mongoose.Schema;
const RecordModel = new Message({
  message: String,
  name: String,
  num: Number,
},{versionKey: false});
module.exports = mongoose.model('using_records', RecordModel);
  • 在使用 schema 对进行数据的插入时,若直接插入,则会在新的集合中多出一个_v 字段,这个代表的是集合的版本号,可以在 schema 中加入 versionKey: false 来删除_v 字段
  • 数据插入:使用 save 方法
const record= new Record({
    message: req.body.message,
    name: req.body.name,
    num: req.body.num,
});
record.save((err, docs) => {if (err) {res.send({ 'status': -1, 'msg': '插入失败'});
  } else {res.send({ 'status': 200, 'msg': '插入成功', 'result':  ''});
  }
});

3.2 数据的查询

  • 使用 find 方法
record.find((err, docs) => {if (err) {res.send({ 'status': -1, 'msg': '参数错误'});
  } else {res.send({ 'status': 200, 'msg': '查询成功', 'result':  docs});
  }
});

3.3 数据的更新

  • 更新一条数据:updateOne
/* 第一个参数为查询参数,第二个为要更新的内容,第三个为回调方法 */
record.updateOne({_id: id}, updateInfo, (err, doc) => {if(err) {res.send({'status': -1, 'msg': '更新失败', 'result': ''});
    } else {res.send({'status': 200, 'msg': '更新成功', 'result': ''});
    }
})
  • 更新多条数据:updateMany
record.updateMany({user_info: {$elemMatch: {user_id: userId, status: 1, is_delete: 1}}}, {$set: {'user_info.$.is_delete': 3}}, (err, doc) => {if(err) {res.send({'status': -1, 'msg': '参数错误'});
    } else {res.send({'status': 200, 'msg': '清空成功'});
    }
})

3.4 数据的删除

/* 第一个为要删除的内容的参数 */
record.findOneAndDelete({_id: req.body.id}, (err, doc) => {if(err) {res.send({'status': -1, 'msg': '删除失败'});
    } else {res.send({'status': 200, 'msg': '删除成功'});
    }
})

4. 数据库的分页操作 (limit 和 skip 方法)

  • limit() 方法为限制数据库每次查询的数据条数;skip(param) 跳过 param 条数据不查询
/* page: 页码;pagesize: 每页的数量 */
let page = req.body.page;
let pagesize = req.body.pagesize;
let queryResult = collection.find(queryCondition).limit(pageSize).skip((page - 1) * pageSize).sort({'_id': -1});
queryResult.exec((err, value) => {if(err) {reject(err);
  } else {resolve({total, value});
  }
})

5. 匹配数据

  • 匹配数据中的数组里的某个对象里的某个字段,使用 $set 来设置对应的值
$set: {'user_info.$.status': 1}
  • $elemMath 只匹配第一条数据,当数组里存在多条一样的数据时,只返回第一条数据
let arr = [
    {
        is_delete: 1,
        name: 'a'
    },
    {
        is_delete: 1,
        name: 'b'
    }
]
{$elemMatch: {is_delete: 1}} 只匹配 arr 的第一条数据 
  • aggregate 匹配多条数据
/* aggregate 聚合操作,$unwind 将数组拆分成单个元素
   * $group 分组依据
   * $sum 统计
   * $project 将返回值进行筛选,是否返回筛选完后的某个字段
   * */
  message.aggregate([
    {
      $match: {
        'user_info.user_id': id,
        'user_info.is_delete': 0
      }
    },
    {$unwind: '$user_info'},
    {
      $group: {_id: {status: '$user_info.status',},
        count: {$sum: 1}
      }
    },
    {
      $project: {
        '_id': 0,
        'status': '$_id.status',
        'count': 1
      }
    }
  ]).then()
  • 对于匹配数组里的某项中的某个字段
let arr = [
    {
        is_delete: 1,
        name: 'a'
    },
    {
        is_delete: 1,
        name: 'b'
    }
]
/* 匹配 arr 中的 name */
$match: {'arr.name': 'a'}
/* 分组筛选 */
$ group: {_id: {name: '$arr.name'}
}
  • 对对象中的数组进行插入数据操作
let obj = {
    id: 1,
    arr: [
        {
            is_delete: 1,
            name: 'a'
        },
        {
            is_delete: 1,
            name: 'b'
        }
    ]
}
{'$push': {arr: {name: 'c', is_delete: 0}}}

正在努力学习中,若对你的学习有帮助,留下你的印记呗(点个赞咯 ^_^)

  • 往期好文推荐:

    • 使用 vue 开发移动端管理后台
    • 实现单行及多行文字超出后加省略号
    • node 之本地服务器图片上传
    • 纯 css 实现瀑布流(multi-column 多列及 flex 布局)
正文完
 0