接着上一篇《Js全栈开发之Sequelize用法详解(MySQL)》来继续学习koa2,上一篇总结了MySQL等关系型数据库的使用和ORM框架Sequelize的用法,本篇将汇总NoSQL类数据库的用法,如MongoDB和Redis等,总结一些平时比较常用的api及语法。
npm install mongoose -save
// 连接数据库
const mongoose = require('mongoose');
mongoose.connect('mongodb://xxx.xxx.xxx.xxx:27017/admin',{
user:'root',
pass:'xxxxxx',
poolSize: 10,
useNewUrlParser: true,
useUnifiedTopology: true
});
const mongodbConn = mongoose.connection;
mongodbConn.on('error', err => {
console.error(err);
});
mongodbConn.once('open', ()=> {
console.log('连接成功!')
})
const mongodbConn = mongoose.connection;
// 声明和创建model对象
const cateqorySchema = new mongoose.Schema({
name:{
type:String,
index:true,
unique:true
},
description: String,
createArt:{
type:Date,
default: Date.now
}
});
const Category = mongodbConn.model('Category',cateqorySchema);
// 插入对象方法1
const categoryObj = new Category({
name:'编程',
description:'编程开发技术类'
});
categoryObj.save(err =>{
if(err){
console.error(err)
return;
}
else{
console.log('save success!');
}
});
// 插入对象方法2
Category.create({
name:'摄影',
description:'摄影户外类'
},(err, category)=>{
if(err){
console.error(err);
}else{
console.log(category);
}
})
// 查找对象
Category.find({
name: '编程'
},(err,res)=>{
if(err){
console.log(err)
}else{
console.log(res);
}
mongodbConn.close();
});
// 更新对象
Category.update({
name: '编程'
},{
description:'技术开发'
}).then((err,res)=>{
if(err){
console.log(err)
}else{
console.log(res);
}
mongodbConn.close();
});
// 删除对象
Category.update({
name: '编程'
}).then((err,res)=>{
if(err){
console.log(err)
}else{
console.log(res);
}
mongodbConn.close();
});
npm install redis -save
const redis = require('redis');
const redisLink = 'redis://xxx.xxx.xxx:6379'
const opts = {
auth_pass: 'xxxxxx',
}
const redisClient = redis.createClient(redisLink, opts)
redisClient
.on('error', err => console.log('------ Redis connection failed ------' + err))
.on('connect', () => console.log('------ Redis connection succeed ------'))
// 储存字符串
redisClient.set('name','dahlin',redis.print)
redisClient.get('name', function(err,value){
if(err) throw err;
console.log('name:'+value);
});
// 用哈希存储数据
redisClient.hmset('dahlin',{
'item':'koa2learn',
'chapter':'use redis'
});
redisClient.hgetall('dahlin', function(err,obj){
console.log(obj)
});
redisClient.hkeys("dahlin",function(err,replies){
replies.forEach(function(reply,i){
console.log(i+"->"+reply);
})
});
// 用列表存取数据
redisClient.lpush('mylist','koa1',redis.print);
redisClient.lpush('mylist','koa2',redis.print);
redisClient.lrange('mylist',0,-1,function(err,items){
if(err){
console.log(err);
}else{
items.forEach(function(item,i){
console.log(i+":"+item);
})
}
});
// 用集合存取数据
redisClient.sadd('myset','koa1',redis.print);
redisClient.sadd('myset','koa2',redis.print);
redisClient.smembers('myset',function(err,items){
if(err){
console.log(err);
}else{
console.log(items);
}
});
//封装redis util/redis.js
const redis = require("redis");
const { promisify } = require('util');
//Redis 命令参考 http://doc.redisfans.com/index.html
/**
*
* @param {*} db 需要切换的DB,不传则默认DB 0
*/
function Client(num){
let db = num || 0
let client = redis.createClient({db});
//需要使用同步函数,按照如下定义即可
this.exists = promisify(client.exists).bind(client);
this.keys = promisify(client.keys).bind(client);
this.set = promisify(client.set).bind(client);
this.get = promisify(client.get).bind(client);
this.del = promisify(client.del).bind(client);
this.incr = promisify(client.incr).bind(client);
this.decr = promisify(client.decr).bind(client);
this.lpush = promisify(client.lpush).bind(client);
this.hexists = promisify(client.hexists).bind(client);
this.hgetall = promisify(client.hgetall).bind(client);
this.hset = promisify(client.hset).bind(client);
this.hmset = promisify(client.hmset).bind(client);
this.hget = promisify(client.hget).bind(client);
this.hincrby = promisify(client.hincrby).bind(client);
this.hdel = promisify(client.hdel).bind(client);
this.hvals = promisify(client.hvals).bind(client);
this.hscan = promisify(client.hscan).bind(client);
this.sadd = promisify(client.sadd).bind(client);
this.smembers = promisify(client.smembers).bind(client);
this.scard = promisify(client.scard).bind(client);
this.srem = promisify(client.srem).bind(client);
return this;
}
module.exports = Client
// 同步方式使用
const Client = require('../util/redis')
let client = new Client(3); //gateway在REDIS中的默认DB 为0
let old = await client.exists(ip);//先查询
if (!old) {
await client.set(ip, value);
}