node.js结合mongodb数据库制作留言本
Ken Ken Coding 7月30日
留言本已经是无处不在了,最近学习了node.js之后,想想要做一个留言本
其实很简单,在做之前,我们要规划一下,留言的步骤
1 首先呢,必须要有一个留言的页面,就如下面:(布局很丑,不管了,将就着看吧)
2 留言提交到哪里去呢,当然是数据库啦,这里的数据库是mongodb,是一个非关系型的数据库,支持key-value键值对存储的数据库,在我的理解,其实就是以对象的形式储存把,这是他命令行工具,也就是客户端
3 就是把储存在数据库的留言取出来,放在页面中
在此之前,我对数据库的操作api进行了一次封装 doa.js
/**
* 封装一个类
* @url 数据库链接地址
* @collectionName 集合的名称
*
* _connect()函数用于查询链接数据库的
* 返回一个promise对象
*
* insert(document,insertMany)函数用于插入文档
*
* query(document)查询文档
*
* del(query,deleteMany)删除文档
*
* update(filter,updater)更新文档
*/
当然,你要用npm install mongodb --save-dev;安装一个依赖库
实现代码如下
01
—
class Doa{
constructor(url,dbName,collectName){
this.url = url;
this.dbName = dbName;
this.collectName = collectName;
}
_connect(){
return new Promise((resolve,reject)=>{
mongo.connect(this.url,(err,client)=>{
if(err){
return reject(err);
}else{
resolve(client);
}
})
})
}
insert(documents,insertMany){
return new Promise((resolve,reject)=>{
this._connect().then(client=>{
// console.log('数据库连接成功');
if(insertMany){
// 插入多条数据
// insertMany是一个布尔值
client.db(this.dbName).collection(this.collectName).insertMany(documents).then(res=>{
resolve(res);
client.close();
}).catch(e=>{
throw new Error(e);
})
return;
}else{
// 插入单条数据
client.db(this.dbName).collection(this.collectName).insertOne(documents).then(res=>{
resolve(res);
client.close();
}).catch(e=>{
throw new Error(e);
})
}
})
})
}
query(documents={},pageConfig={count:0,page:0}){
return new Promise((resolve,reject)=>{
this._connect().then(client=>{
let arr = [];
// 查询文档
let cursor = client.db(this.dbName)
.collection(this.collectName)
.find(documents)
.limit(pageConfig.count)
.skip((pageConfig.page-1) * pageConfig.count);
// console.log(cursor);
// each查询每一条数据
cursor.each((err,data)=>{
// console.log(data);
if(err){
// 如果存在错误
// 直接放回
reject(err);
}
// data最后一条数据为null
// 以此判断依据
if(data!==null){
// 将每一条数据放入数组中
arr.push(data);
}else{
// 当data为null时把数据返回出去
// 并且关闭数据库
resolve(arr);
client.close();
}
})
// resolve(cursor);
}).catch(e=>{
reject(e);
})
})
}
del(query,deleteMany){
// 步骤跟insert()函数相似
return new Promise((resolve,reject)=>{
this._connect().then(client=>{
if(deleteMany){
client.db(this.dbName)
.collection(collectName)
.deleteMany(query)
.then(res=>{
resolve(res);
client.close();
}).catch(e=>{
reject(e);
})
}else{
client.db(this.dbName)
.collection(collectName)
.deleteOne(query)
.then(res=>{
resolve(res);
client.close();
}).catch(e=>{
reject(e);
})
}
}).catch(e=>{
reject(e);
})
})
}
update(filter,updater){
return new Promise((resolve,reject)=>{
this._connect().then(client=>{
let updaterCopy = {$set:updater};
client.db(this.dbName)
.collection(this.collectName)
.updateMany(filter,updaterCopy)
.then(res=>{
resolve(res);
client.close();
}).catch(e=>{
reject(e);
});
}).catch(e=>{
reject(e);
})
})
}
}
接下来实现后台代码:
我们来看一下我的留言本目录吧:
看一下向导吧
最终浏览的效果是
源码已经放在我的github地址上啦
https://github.com/KenNaNa/mongoose