简体   繁体   中英

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.

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:

  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:

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".

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.

The query is async, so you need to add a handler to the returned promise:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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