手把手教你搭建一个【文件共享平台】系列教程第四话——node.js与mongodb的交互,封装基本操作

本话概要

我们在第二篇系列文章中已经教大家如何安装mongodb,以及如何发布数据库服务。本话在此基础上,教大家在node.js代码中与mongodb数据库交互操作的代码实现,并且教大家如何利用NosqlClient软件,用图形化的界面访问并操作mongodb数据库的数据。
学会本章的内容,你就可以自由地设计自己的数据库表结构,以及CURD操作。🌕

mongodb介绍

在这里插入图片描述
MongoDB(来自于英文单词“Humongous”,中文含义为“庞大”)是可以应用于各种规模的企业、各个行业以及各类应用程序的开源数据库。
MongoDB 是一个基于分布式文件存储的数据库。由 C++ 语言编写。旨在为 WEB 应用提供可扩展的高性能数据存储解决方案。
MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。

常规操作

连接

要操作数据库,首先必须连接数据库。我们首先创建一个lib文件夹,再创建一个dbOpr.js的文件夹,用于封装数据库的所有操作。文件目录如下:

  • shareFile_server/
    • lib/
      • dbOpr.js
      • MongoCfg.js //数据库连接配置文件
    • 其他文件及文件夹

在MongoCfg.js中,我们写下如下配置:

const url = "mongodb://localhost:27017";//数据库连接url
const dbName = "sp_server"//数据库名
const option = {//连接参数
	useNewUrlParser:true,
	useUnifiedTopology:true
}

module.exports = {
	url:url,
	dbName:dbName,
	option:option
}

在dbOpr.js中,我们按照如下方式连接数据库:

const MongoClient = require('mongodb').MongoClient;// 引入MongoClient包
const { url, dbName, collectionName_User, option } = require('./MongoCfg.js');// 导入连接配置

MongoClient.connect(url,option,(err,client)=>{
	if(err) throw err;
	console.log('connect to db server');
	let db = client.db(dbName);
	client.close()
})

查询

mongodb中查询的方法是find()。如果我们要查找集合user中age为22的所有document,那么我们应该如下操作:

let collection = db.collection('user');
collection.find({
	'age':22
}).toArray(function(err,docs){
	if(err) throw err;
	callback(docs)
})

当然,如果我们想要这个方法更通用,我们可以添加limit,skip这些操作符。完整的findDocument函数(查询)代码如下:

// 查询函数lib/db/findDocument.js
/**
 * @param {Object} db
 * @param {String} collectionName
 * @param {Object} msg
 * @param {Function} callback
 * msg格式如下:
 * {
 * key:Array,//筛选的字段名
 * value:Array,//筛选的字段值
 * limit:Number,//最大查询结果数
 * skip:Number//跳过记录数
 * }
 */
const findDocument = function(db,collectionName,msg,callback){
	let collection = db.collection(collectionName);
	let whereobj = {};
	msg.key.forEach((item,index)=>{
		whereobj[item] = msg.value[index]
	})
	collection.find(whereobj).limit(msg.limit ? msg.limit : 100).skip(msg.skip ? msg.skip : 0).toArray(function(err,docs){
		if(err) throw err;
		callback(docs)
	})
}

module.exports = findDocument;

这样的写法十分通用,可以满足多种查询需求。

更新

为了满足通用的需求,我们同样设计了更新多条记录的方法。Mongodb更新多条记录的操作是updateMany()。设计如下:

// 更新函数 lib/db/updateDocument.js
/**
 * @param {Object} db
 * @param {String} collectionName
 * @param {Object} msg
 * @param {Function} callback
 * msg格式如下:
 * {
 * wherekey:Array,//筛选的字段名
 * wherevalue:Array,//筛选的字段值
 * updatekey:Array,//更新字段
 * updatevalue:Array//更新字段值
 * }
 */
const updateDocument = function(db,collectionName,msg,callback){
	let collection = db.collection(collectionName);
	let whereobj = {};
	let setobj = {};
	msg.wherekey.forEach((item,index)=>{
		whereobj[item] = msg.wherevalue[index]
	})
	msg.updatekey.forEach((item,index)=>{
		setobj[item] = msg.updatevalue[index]
	})
	collection.updateMany(whereobj,
		{$set:setobj},
		function(err,result){
			if(err) throw err;
			console.log('update success');
			callback(result);
		})
}

module.exports = updateDocument;

插入

Mongodb的插入多条记录的方法是insertMany()。设计如下:

// 插入函数 lib/db/insertDocument.js
/**
 * @param {Object} db
 * @param {String} collectionName
 * @param {Object} msg
 * @param {Function} callback
 * msg格式如下:
 * [{
 * 字段1:字段值1,
 * 字段2:字段值2,
 * ...
 * },...]
 */
const insertDocument = function(db,collectionName,msg,callback){
	let collection = db.collection(collectionName);
	collection.insertMany(msg,function(err,result){
		if(err) throw err;
		console.log('insert success');
		callback(result);
	})
}

module.exports = insertDocument;

删除

删除函数为deleteMany(),设计如下:

// 删除函数 lib/db/deleteDocument.js
/**
 * @param {Object} db
 * @param {String} collectionName
 * @param {Object} msg
 * @param {Function} callback
 * msg格式如下:
 * {
 * key:Array,//筛选的字段
 * value:Array//筛选的字段值
 * }
 */
const deleteDocument = function(db,collectionName,msg,callback){
	let collection = db.collection(collectionName);
	let del = {}
	msg.key.forEach((item,index)=>{
		del[item] = msg.value[index]
	})
	collection.deleteMany(del,function(err,res){
		if(err) throw err;
		callback(res);
	})
}

module.exports = deleteDocument;

dbOpr.js的完整代码(集成)

这些方法设计的结构都十分相近,就是为了方便集成起来。我用一个操作类MongoOpr将这些函数统一到类中。具体代码如下:

const MongoClient = require('mongodb').MongoClient;
const { url, dbName, collectionName_User, option } = require('./MongoCfg.js');
const deleteDocument = require('./db/deleteDocument');//删
const findDocument = require('./db/findDocument');//查
const insertDocument = require('./db/insertDocument');//增
const updateDocument = require('./db/updateDocument');//改

//用集合名对数据库操作类进行初始化
class MongoOpr{
	constructor(collectionName){
		this.CN = collectionName;
	}
	insertMsg(msg){
		MongoClient.connect(url,option,(err,client)=>{
			if(err) throw err;
			console.log('connect to db server');
			let db = client.db(dbName);
			insertDocument(db,this.CN,msg,(res)=>{
				// console.log(res)
				client.close()
			})
		})
	}
	deleteMsg(msg){
		MongoClient.connect(url,option,(err,client)=>{
			if(err) throw err;
			let db = client.db(dbName);
			deleteDocument(db,this.CN,msg,(res)=>{
				// console.log(res)
				client.close()
			})
		})
	}
	findMsg(msg){
		return new Promise((resolve,reject)=>{
			MongoClient.connect(url,option,(err,client)=>{
				if(err) throw err;
				let db = client.db(dbName);
				findDocument(db,this.CN,msg,(res)=>{
					client.close();
					resolve(res);
				})
			})
		})
	}
	updateMsg(msg){
		MongoClient.connect(url,option,(err,client)=>{
			if(err) throw err;
			let db = client.db(dbName);
			updateDocument(db,this.CN,msg,(res)=>{
				client.close()
			})
		})
	}
}

module.exports = MongoOpr;

使用方法如下:

const MongoOpr = require('../lib/dbOpr');
const MongoDB = new MongoOpr(集合名);
//方法列表
MongoDB.insertMsg(...);
MongoDB.deleteMsg(...);
MongoDB.findMsg(...);
MongoDB.updateMsg(...);

是不是很容易啊🌝

NosqlClient的使用方法

在这里插入图片描述
NosqlClient是为mongodb打造的一款图形界面操作软件,下载链接
使用NosqlClient可以可视化操作mongodb中的数据。下面我教大家如何连接数据库,以及一些基本操作。
我们首先打开软件,默认是未连接的状态,如图。我们点击右上角的connect按钮
在这里插入图片描述
点击create new,进入创建连接页面,我们输入connection name,ip,port,database name。最后点击save changes。连接就创建好了。
在这里插入图片描述
点击connect now,nosqlclient就连接上数据库了。
在这里插入图片描述
我们在左边菜单栏右键collections,可以创建新的collection。创建好后,可以在collections栏下看到新建的collection。如图
在这里插入图片描述
右边有该collection的详细信息。
同时,我们可以在右侧的Query File中,执行数据库CURD操作。比如默认的find()操作,点击Execute,结果会在下方显示。插入、更新、删除同理。你需要在selector中书写具体的操作代码(json格式)
在这里插入图片描述
这样,你就可以在该软件中操作mongodb数据库了,是不是很方便?🌞

下期预告

下一期,我将教大家如何在后端实现用户功能的路由,包括注册、登录、用户信息等。
下期再见👋

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

HouGISer

HouGiser需要你的鼓励~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值