2014-09-12 52 views
0

我想在幾個視圖中提供一個類別列表:將它們可視化爲一個列表,將它們作爲選項加載到創建產品表單中...爲了重用這些類別,我有將DAO從控制器中分離出來。問題是如何將返回的類別categoryDao傳遞到categoryController從控制器中分離DAO以實現可重用性

這是我的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); 

回答

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); 
+0

在實際的使用情況中,我們想渲染除類別之外的其他東西。例如,爲了給'editForm'一個產品,我們可以'res.render'產品信息來編輯除了可以選擇的類別。所以我們必須從'editForm'中調用'productDao'。我們如何做到這一點? – arymeo 2014-09-12 14:26:33

+0

@arymeo這是最好的一個新問題。 – JohnnyHK 2014-09-12 14:47:18

+0

好的,謝謝@JohnnyHK – arymeo 2014-09-12 15:11:29