Javascript 如何构造我的nodejs代码?胖型/瘦型控制器

Javascript 如何构造我的nodejs代码?胖型/瘦型控制器,javascript,node.js,mongodb,model-view-controller,mongoose,Javascript,Node.js,Mongodb,Model View Controller,Mongoose,我的代码可以工作,但我知道最好有胖的模型和瘦的控制器 然而,我使用3种不同的型号,不幸的是,我的控制器太胖了。组织此代码的最佳方式是什么(使用胖模型/瘦控制器概念)?我一直在阅读代码结构,但我有点不确定最佳实践 控制器: var Product = require('../models/product'); var Collection = require('../models/collection'); var Vote = require('../models/vote'); export

我的代码可以工作,但我知道最好有胖的模型和瘦的控制器

然而,我使用3种不同的型号,不幸的是,我的控制器太胖了。组织此代码的最佳方式是什么(使用胖模型/瘦控制器概念)?我一直在阅读代码结构,但我有点不确定最佳实践

控制器:

var Product = require('../models/product');
var Collection = require('../models/collection');
var Vote = require('../models/vote');

exports.topSearch = function(req, res) {
  console.log(req.body, "search product")

  Product.search({
      query_string: {
        query: req.body.search
      }
    },req.body.searchObject,
    function(err, results) {
      if (err) console.log('ERR', err);
      if (results) {
        var data = results.hits.hits;

        Vote.find({
          user: req.user._id
        }, function(err, votes) {
          if (!err) {
            for (var i = 0; i < votes.length; i++) {
              for (var j = 0; j < data.length; j++) {
                if (data[j]['_id'] == votes[i]['product']) {
                  data[j]['voteId'] = votes[i]['_id'];
                  data[j]['userVote'] = votes[i]['vote'];
                }
              }
            }
          }

        Collection.find({
          user: req.user._id
        }, function(err, collections) {
          if (!err) {
            for (var i = 0; i < collections.length; i++) {
              for (var j = 0; j < data.length; j++) {
                if (data[j]['_id'] == collections[i]['product']) {
                  console.log('match')
                  data[j]['collected'] = true;
                  data[j]['collectId'] = collections[i]['_id'];
                  data[j]['favorite'] = collections[i]['favorite'];
                } else if (data[j]['_id'] !== collections[i]['product'] && data[j]['collected'] !== true) {
                  data[j]['collected'] = false;
                }
              }
            }
            res.send(data);
          }
        });
      });

      } else {
        res.send({
          errmsg: 'results not defined'
        })
      }
    });
};

您可以在“模型”或“函数”下创建一个单独的文件,在该文件中,您可以执行与“topSearch”相关的所有基于模型的处理,然后只需在控制器内调用单个方法

使用类似于async.js的方法来更好地处理回调和流

我个人遵循本回购协议中定义的文件夹结构

有时我会根据复杂性将子文件夹添加到模型和控制器中

常用的select查询可以直接导出为独立函数,以便于重用

  app.post('/products-search', users.ensureAuthenticated, products.topSearch);