专栏名称: SegmentFault思否
SegmentFault (www.sf.gg)开发者社区,是中国年轻开发者喜爱的极客社区,我们为开发者提供最纯粹的技术交流和分享平台。
目录
相关文章推荐
OSC开源社区  ·  升级到Svelte ... ·  3 天前  
程序猿  ·  “我真的受够了Ubuntu!” ·  昨天  
程序员的那些事  ·  惊!小偷“零元购”后竟向 DeepSeek ... ·  2 天前  
程序员的那些事  ·  成人玩偶 + ... ·  3 天前  
51好读  ›  专栏  ›  SegmentFault思否

mongodb 数据库及数据分页

SegmentFault思否  · 公众号  · 程序员  · 2020-03-13 11:56

正文

本文转载于 SegmentFault 社区
作者:小小蚊子

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


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');
});



数据类型



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

数据类型有: String,Number,Date,Buffer,Boolean,ObjectId,Array,Mixed,Map,Decimal128

在数据库直接用 insert 方法进行数据插入时,若不强制指定数字的类型,则默认是插入 double 型数字。


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': '删除成功'});
}
})

数据库的分页操作



数据库的分页操作 (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});
}
})








请到「今天看啥」查看全文