我有以下使用Mongoose和MongoDB的Node.js代码段。
如何使UserService
数据库不可知,以便我可以将MongoDB交换为MySQL?
app.js
app.get("/users", async (req, res, next) => {
try {
const users = await UserService.listUsers();
res.json(users);
} catch (error) {
next(error);
}
});
index.js
const User = require("./user_model");
const UserService = require("./user_service");
module.exports = UserService(User);
user_service.js
const listUsers = User => () => {
return User.find({});
};
module.exports = User => {
return {
listUsers: listUsers(User)
};
};
user_model.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const UserSchema = new Schema({
name: String,
birthday: String,
createdAt: { type: Date, default: Date.now }
});
module.exports = mongoose.model("User", UserSchema);