日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪(fǎng)問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 运维知识 > 数据库 >内容正文

数据库

mongodb连接失败_mongodb 数据库及数据分页

發(fā)布時(shí)間:2023/11/30 数据库 41 豆豆
生活随笔 收集整理的這篇文章主要介紹了 mongodb连接失败_mongodb 数据库及数据分页 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
本文轉(zhuǎn)載于 SegmentFault 社區(qū)作者:小小蚊子
? ??在做自己的一個(gè)小項(xiàng)目時(shí),新學(xué)習(xí)了 mongodb非關(guān)系型數(shù)據(jù)庫(kù),使用了 mongoose封裝好的查詢(xún)方法,包括數(shù)據(jù)庫(kù)分頁(yè)用到的limit和 skip 方法,這里記錄下。

??

mongodb 數(shù)據(jù)庫(kù)連接

參照官網(wǎng)文檔對(duì)應(yīng)的參數(shù)如下:mongodb://[username:password@]host1[:port1][,host2[:port2],...[,hostN[:portN]]][/[database][?options]]使用 mongoose進(jìn)行數(shù)據(jù)庫(kù)的連接: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)警告信息:要求使用新的編譯方式,則在連接的時(shí)候加上 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ù)庫(kù)時(shí),對(duì)連接操作進(jìn)行監(jiān)聽(tīng)處理mongoose.connection.on('connected', function() {
console.log('Mongoose connection open to ' + dataBaseUrl);
});
/* 連接數(shù)據(jù)庫(kù)異常 */
mongoose.connection.on('error', function(err) {
console.log('Mongoose connection error:' + err);
});
/* 連接數(shù)據(jù)庫(kù)斷開(kāi) */
mongoose.connection.on('disconnected', function() {
console.log('Mongoose connection disconnected');
});

數(shù)據(jù)類(lèi)型

數(shù)據(jù)類(lèi)型 (mongoose 中提供的 schemaTypes)數(shù)據(jù)類(lèi)型有:String,Number,Date,Buffer,Boolean,ObjectId,Array,Mixed,Map,Decimal128在數(shù)據(jù)庫(kù)直接用 insert 方法進(jìn)行數(shù)據(jù)插入時(shí),若不強(qiáng)制指定數(shù)字的類(lèi)型,則默認(rèn)是插入double型數(shù)字。

mongoose 對(duì)數(shù)據(jù)庫(kù)操作的方法

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對(duì)進(jìn)行數(shù)據(jù)的插入時(shí),若直接插入,則會(huì)在新的集合中多出一個(gè)_v字段,這個(gè)代表的是集合的版本號(hào),可以在 schema中加入versionKey: false來(lái)刪除 _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ù)的查詢(xún)

使用find 方法record.find((err, docs) => {
if (err) {
res.send({ 'status': -1, 'msg': '參數(shù)錯(cuò)誤' });
} else {
res.send({ 'status': 200, 'msg': '查詢(xún)成功', 'result': docs});
}
});

3.3 數(shù)據(jù)的更新

更新一條數(shù)據(jù):updateOne/* 第一個(gè)參數(shù)為查詢(xún)參數(shù),第二個(gè)為要更新的內(nèi)容,第三個(gè)為回調(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ù)錯(cuò)誤'});
} else {
res.send({'status': 200, 'msg': '清空成功'});
}
})

3.4 數(shù)據(jù)的刪除

/* 第一個(gè)為要?jiǎng)h除的內(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ù)庫(kù)的分頁(yè)操作

數(shù)據(jù)庫(kù)的分頁(yè)操作(limit 和 skip 方法)limit()方法為限制數(shù)據(jù)庫(kù)每次查詢(xún)的數(shù)據(jù)條數(shù);skip(param) 跳過(guò) param 條數(shù)據(jù)不查詢(xún)。/* page: 頁(yè)碼;pagesize: 每頁(yè)的數(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ù)組里的某個(gè)對(duì)象里的某個(gè)字段,使用 $set 來(lái)設(shè)置對(duì)應(yīng)的值$set:?{'user_info.$.status':?1}$elemMat?只匹配第一條數(shù)據(jù),當(dāng)數(shù)組里存在多條一樣的數(shù)據(jù)時(shí),只返回第一條數(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ù)組拆分成單個(gè)元素
* $group 分組依據(jù)
* $sum 統(tǒng)計(jì)
* $project 將返回值進(jìn)行篩選,是否返回篩選完后的某個(gè)字段
* */
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()對(duì)于匹配數(shù)組里的某項(xiàng)中的某個(gè)字段/* aggregate聚合操作,$unwind將數(shù)組拆分成單個(gè)元素
* $group 分組依據(jù)
* $sum 統(tǒng)計(jì)
* $project 將返回值進(jìn)行篩選,是否返回篩選完后的某個(gè)字段
* */
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()對(duì)對(duì)象中的數(shù)組進(jìn)行插入數(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 数据库及数据分页的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。