在Node.js中,常见的数据库有MySQL、MongoDB、Redis等。下面是各类数据库常用方法的封装示例。
const mysql = require('mysql');
// 创建连接池
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'password',
database: 'mydb',
connectionLimit: 10
});
// 查询数据
function query(sql, values) {
return new Promise((resolve, reject) => {
pool.getConnection((err, connection) => {
if (err) {
reject(err);
} else {
connection.query(sql, values, (err, results) => {
connection.release();
if (err) {
reject(err);
} else {
resolve(results);
}
});
}
});
});
}
module.exports = {
query
};
const mongoose = require('mongoose');
// 连接数据库
mongoose.connect('mongodb://localhost/mydb', {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
// 定义数据模型
const userSchema = new mongoose.Schema({
name: String,
age: Number
});
const User = mongoose.model('User', userSchema);
// 查询数据
function findUser(query) {
return User.find(query).exec();
}
module.exports = {
findUser
};
const redis = require('redis');
const client = redis.createClient();
// 设置数据
function set(key, value) {
return new Promise((resolve, reject) => {
client.set(key, value, (err, reply) => {
if (err) {
reject(err);
} else {
resolve(reply);
}
});
});
}
// 获取数据
function get(key) {
return new Promise((resolve, reject) => {
client.get(key, (err, reply) => {
if (err) {
reject(err);
} else {
resolve(reply);
}
});
});
}
module.exports = {
set,
get
};
这些封装示例只是简单的示范,实际应用中还需要根据具体的业务需求进行适当的封装和错误处理。