如何使此设计数据库不可知?

时间:2018-06-07 02:31:58

标签: mysql node.js mongodb

我有以下使用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);

信用:https://youtu.be/ACzMbQEq_tw

0 个答案:

没有答案