mongodb连接失败_mongodb 数据库及数据分页
生活随笔
收集整理的這篇文章主要介紹了
mongodb连接失败_mongodb 数据库及数据分页
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
本文轉(zhuǎn)載于 SegmentFault 社區(qū)作者:小小蚊子
? ??在做自己的一個小項目時,新學(xué)習(xí)了 mongodb非關(guān)系型數(shù)據(jù)庫,使用了 mongoose封裝好的查詢方法,包括數(shù)據(jù)庫分頁用到的limit和 skip 方法,這里記錄下。
? `mongodb://${config.admin.username}:${config.admin.pwd}@${config.host}/share-resource`
: `mongodb://${config.host}/share-resource`;
mongoose.connect(dataBaseUrl, { useNewUrlParser: true });若出現(xiàn)警告信息:要求使用新的編譯方式,則在連接的時候加上 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 });在連接數(shù)據(jù)庫時,對連接操作進行監(jiān)聽處理mongoose.connection.on('connected', function() {
console.log('Mongoose connection open to ' + dataBaseUrl);
});
/* 連接數(shù)據(jù)庫異常 */
mongoose.connection.on('error', function(err) {
console.log('Mongoose connection error:' + err);
});
/* 連接數(shù)據(jù)庫斷開 */
mongoose.connection.on('disconnected', function() {
console.log('Mongoose connection disconnected');
});
const Message= mongoose.Schema;
const RecordModel = new Message({
message: String,
name: String,
num: Number,
},{
versionKey: false
});
module.exports = mongoose.model('using_records', RecordModel);在使用 schema對進行數(shù)據(jù)的插入時,若直接插入,則會在新的集合中多出一個_v字段,這個代表的是集合的版本號,可以在 schema中加入versionKey: false來刪除 _v字段數(shù)據(jù)插入:使用 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': ''});
}
});
if (err) {
res.send({ 'status': -1, 'msg': '參數(shù)錯誤' });
} 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': ''});
}
})更新多條數(shù)據(jù):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': '參數(shù)錯誤'});
} 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': '刪除成功'});
}
})
? ?
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});
}
})
{
is_delete: 1,
name: 'a'
},
{
is_delete: 1,
name: 'b'
}
]
{$elemMatch: {is_delete: 1}}只匹配arr的第一條數(shù)據(jù)aggregate 匹配多條數(shù)據(jù)/* aggregate聚合操作,$unwind將數(shù)組拆分成單個元素
* $group 分組依據(jù)
* $sum 統(tǒng)計
* $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()對于匹配數(shù)組里的某項中的某個字段/* aggregate聚合操作,$unwind將數(shù)組拆分成單個元素
* $group 分組依據(jù)
* $sum 統(tǒng)計
* $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()對對象中的數(shù)組進行插入數(shù)據(jù)操作let arr = [
{
is_delete: 1,
name: 'a'
},
{
is_delete: 1,
name: 'b'
}
]
/* 匹配arr中的name */
$match: {
'arr.name': 'a'
}
/* 分組篩選 */
$ group: {
_id: {name: '$arr.name'}
}?-?END -
? ??在做自己的一個小項目時,新學(xué)習(xí)了 mongodb非關(guān)系型數(shù)據(jù)庫,使用了 mongoose封裝好的查詢方法,包括數(shù)據(jù)庫分頁用到的limit和 skip 方法,這里記錄下。
??
一
mongodb 數(shù)據(jù)庫連接
參照官網(wǎng)文檔對應(yīng)的參數(shù)如下:mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]使用 mongoose進行數(shù)據(jù)庫的連接: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 });若出現(xiàn)警告信息:要求使用新的編譯方式,則在連接的時候加上 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 });在連接數(shù)據(jù)庫時,對連接操作進行監(jiān)聽處理mongoose.connection.on('connected', function() {
console.log('Mongoose connection open to ' + dataBaseUrl);
});
/* 連接數(shù)據(jù)庫異常 */
mongoose.connection.on('error', function(err) {
console.log('Mongoose connection error:' + err);
});
/* 連接數(shù)據(jù)庫斷開 */
mongoose.connection.on('disconnected', function() {
console.log('Mongoose connection disconnected');
});
二
數(shù)據(jù)類型
數(shù)據(jù)類型 (mongoose 中提供的 schemaTypes)數(shù)據(jù)類型有:String,Number,Date,Buffer,Boolean,ObjectId,Array,Mixed,Map,Decimal128在數(shù)據(jù)庫直接用 insert 方法進行數(shù)據(jù)插入時,若不強制指定數(shù)字的類型,則默認(rèn)是插入double型數(shù)字。三
mongoose 對數(shù)據(jù)庫操作的方法
3.1 數(shù)據(jù)的插入
先要新建 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對進行數(shù)據(jù)的插入時,若直接插入,則會在新的集合中多出一個_v字段,這個代表的是集合的版本號,可以在 schema中加入versionKey: false來刪除 _v字段數(shù)據(jù)插入:使用 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 數(shù)據(jù)的查詢
使用find 方法record.find((err, docs) => {if (err) {
res.send({ 'status': -1, 'msg': '參數(shù)錯誤' });
} else {
res.send({ 'status': 200, 'msg': '查詢成功', 'result': docs});
}
});
3.3 數(shù)據(jù)的更新
更新一條數(shù)據(jù):updateOne/* 第一個參數(shù)為查詢參數(shù),第二個為要更新的內(nèi)容,第三個為回調(diào)方法 */record.updateOne({_id: id}, updateInfo, (err, doc) => {
if(err) {
res.send({'status': -1, 'msg': '更新失敗', 'result': ''});
} else {
res.send({'status': 200, 'msg': '更新成功', 'result': ''});
}
})更新多條數(shù)據(jù):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': '參數(shù)錯誤'});
} else {
res.send({'status': 200, 'msg': '清空成功'});
}
})
3.4 數(shù)據(jù)的刪除
/* 第一個為要刪除的內(nèi)容的參數(shù) */record.findOneAndDelete({_id: req.body.id}, (err, doc) => {
if(err) {
res.send({'status': -1, 'msg': '刪除失敗'});
} else {
res.send({'status': 200, 'msg': '刪除成功'});
}
})
? ?
四
數(shù)據(jù)庫的分頁操作
數(shù)據(jù)庫的分頁操作(limit 和 skip 方法)limit()方法為限制數(shù)據(jù)庫每次查詢的數(shù)據(jù)條數(shù);skip(param) 跳過 param 條數(shù)據(jù)不查詢。/* page: 頁碼;pagesize: 每頁的數(shù)量 */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});
}
})
五
匹配數(shù)據(jù)
匹配數(shù)據(jù)中的數(shù)組里的某個對象里的某個字段,使用 $set 來設(shè)置對應(yīng)的值$set:?{'user_info.$.status':?1}$elemMat?只匹配第一條數(shù)據(jù),當(dāng)數(shù)組里存在多條一樣的數(shù)據(jù)時,只返回第一條數(shù)據(jù)let arr = [{
is_delete: 1,
name: 'a'
},
{
is_delete: 1,
name: 'b'
}
]
{$elemMatch: {is_delete: 1}}只匹配arr的第一條數(shù)據(jù)aggregate 匹配多條數(shù)據(jù)/* aggregate聚合操作,$unwind將數(shù)組拆分成單個元素
* $group 分組依據(jù)
* $sum 統(tǒng)計
* $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()對于匹配數(shù)組里的某項中的某個字段/* aggregate聚合操作,$unwind將數(shù)組拆分成單個元素
* $group 分組依據(jù)
* $sum 統(tǒng)計
* $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()對對象中的數(shù)組進行插入數(shù)據(jù)操作let arr = [
{
is_delete: 1,
name: 'a'
},
{
is_delete: 1,
name: 'b'
}
]
/* 匹配arr中的name */
$match: {
'arr.name': 'a'
}
/* 分組篩選 */
$ group: {
_id: {name: '$arr.name'}
}?-?END -
總結(jié)
以上是生活随笔為你收集整理的mongodb连接失败_mongodb 数据库及数据分页的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 原神飘浮秘灵活动怎么玩
- 下一篇: mysql 关联查询_Mysql查询优化