简体   繁体   English

如何通过模型和控制器之间的顺序发送查询结果

[英]How to send a query result with sequelize between model and controller

my problem is the following: 我的问题如下:

I have nodejs+expressjs and then generated an mvc project with generator-express so I have mysql+sequelize+gulp app. 我有nodejs + expressjs,然后用generator-express生成了一个mvc项目,所以我有mysql + sequelize + gulp应用程序。

I connected to the db and made a query in the model, but i can't pass the result to the controller and print it in the screen. 我连接到数据库并在模型中进行了查询,但是我无法将结果传递给控制器​​并在屏幕上打印出来。

Instead of that I get an error that the variable is undefined. 取而代之的是,我得到一个变量未定义的错误。

The code for model (regiones.js) is: 模型(regiones.js)的代码为:

  module.exports = function (sequelize, DataTypes) {

  var regiones = sequelize.define('regiones', {
    idregion: DataTypes.INTEGER,
    nombre: DataTypes.STRING
  }, {
    classMethods:    {
            encontrar : function(){ sequelize
                                    .query('SELECT * FROM regiones', { raw: true })
                                    .spread(function(resul, m){console.log(resul); return resul;}); }   
      }
  });
    return regiones

};  

the code for controller (home.js) is: 控制器(home.js)的代码为:

var express = require('express'),
  router = express.Router(),
  db = require('../models');

module.exports = function (app) {
  app.use('/', router);
};


router.get('/', function (req, res, next) {

        resu = db.regiones.encontrar();
        console.log("resu is : "+resu);
        var arreglo = [];
        for(i=0;i<resu.length;i++){
            arreglo.push(resu[i].nombre);
        }

         db.Article.findAll().then(function (articles) {
            res.render('index', {

             title: arreglo[1],
             articles: articles
            });
        });
});

"regiones" (sorry because the names in spanish) has "idregiones" and "nombre". “区域”(抱歉,因为用西班牙语命名)具有“ idregiones”和“ nombre”。

Basically I want to know how to get the result of the query in the controller. 基本上我想知道如何在控制器中获取查询结果。

The index prints only: 索引仅打印:

Cannot read property 'length' of undefined TypeError: Cannot read property 'length' of undefined at C:\Users\Erick\farma1\app\controllers\home.js:15:17 at Layer.handle [as handle_request] 

and the console prints all tuples in model, but in controller prints: 并且控制台在模型中打印所有元组,但在控制器中打印:

resu is : undefined

I've search a lot, but it seems a theoretical problem of me. 我进行了很多搜索,但这似乎是我的理论问题。

Thanks :) 谢谢 :)

Your encontrar function does not return anything, that's why you are getting undefined. 您的encontrar函数不返回任何内容,这就是为什么您未定义的原因。

The query is async, so you need to add a handler to the returned promise: 该查询是异步的,因此您需要向返回的Promise添加一个处理程序:

db.regiones.encontrar().then(function (resu) {...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM