将DAO与控制器分离以实现可重用性

时间:2014-09-12 11:56:27

标签: node.js express mongoose dao separation-of-concerns

我希望在多个视图中提供类别列表:将它们可视化为列表,将它们作为选项加载到创建产品表单中......为了重用这些类别,我必须将DAO与控制器分开。问题是如何将categoryDao中返回的类别传递到categoryController

这是我的MVC文字代码与我的问题:

// categoryDao.js
var Category = mongoose.model('Category');
exports.allCategories = function() {
    Category.find().exec(function(err, categories) {
        console.log(categories); // is properly defined

        // I don't want to render categories like:
        res.render('categories', {allCategories : categories});

        // insted, I want to return them from within this callback and make them available in the categoryController.js. But you know
        return categories; // is not quite right
    }
    // and of course
    console.log(categories); // is undefined
}

// categoryController.js
var categoryDao = require ('./categoryDao.js');
exports.all = function(req, res) {
    // make allCategories available in a list view
    res.render('categories', {allCategories : categoryDao.allCategories});
}

// productController.js
var categoryDao = require ('./categoryDao.js');
exports.createForm = function(req, res) {
    // make allCategories available in a select element in the create product form
    res.render('create', {allCategories : categoryDao.allCategories});
}

// categoryRoutes.js
var categoryController = require ('./categoryController.js');
app.route('/categories').get(categoryController.all);

1 个答案:

答案 0 :(得分:0)

您无法从方法返回异步结果,而是需要使用回调。

// categoryDao.js
var Category = mongoose.model('Category');
exports.allCategories = function(callback) {
    Category.find().exec(function(err, categories) {
        console.log(categories);

        // Deliver the results to the caller via the callback they provided
        callback(err, categories);
    }
}

// categoryController.js
var categoryDao = require ('./categoryDao.js');
exports.all = function(req, res) {
    // make allCategories available in a list view
    categoryDao.allCategories(function(err, categories) {
        res.render('categories', {allCategories : categories});
    });
}

// productController.js
var categoryDao = require ('./categoryDao.js');
exports.createForm = function(req, res) {
    // make allCategories available in a select element in the create product form
    categoryDao.allCategories(function(err, categories) {
        res.render('create', {allCategories : categories});
    });
}

// categoryRoutes.js
var categoryController = require ('./categoryController.js');
app.route('/categories').get(categoryController.all);