在做自己的一个小项目时,新学习了mongodb非关系型数据库,使用了mongoose封装好的查询方法,包括数据库分页用到的limit和skip方法,这里记录下。
mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]
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 });
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');
});
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);
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': ''});
}
});
record.find((err, docs) => {
if (err) {
res.send({ 'status': -1, 'msg': '参数错误' });
} else {
res.send({ 'status': 200, 'msg': '查询成功', 'result': docs});
}
});
/* 第一个参数为查询参数,第二个为要更新的内容,第三个为回调方法 */
record.updateOne({_id: id}, updateInfo, (err, doc) => {
if(err) {
res.send({'status': -1, 'msg': '更新失败', 'result': ''});
} else {
res.send({'status': 200, 'msg': '更新成功', 'result': ''});
}
})
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': '清空成功'});
}
})
/* 第一个为要删除的内容的参数 */
record.findOneAndDelete({_id: req.body.id}, (err, doc) => {
if(err) {
res.send({'status': -1, 'msg': '删除失败'});
} else {
res.send({'status': 200, 'msg': '删除成功'});
}
})
/* 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});
}
})
$set: {'user_info.$.status': 1}
let arr = [
{
is_delete: 1,
name: 'a'
},
{
is_delete: 1,
name: 'b'
}
]
{$elemMatch: {is_delete: 1}}只匹配arr的第一条数据
/* 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}}}