在做自己的一个小项目时,新学习了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: trueDeprecationWarning: 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': ''}); }})更新多条数据:updateManyrecord.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}}}正在努力学习中,若对你的学习有帮助,留下你的印记呗(点个赞咯^_^)往期好文推荐:
...