ExpressJS - Sequelize - 查询结果未填充在对象中

时间:2015-10-16 12:24:53

标签: node.js express sequelize.js

我有一个路由设置,用于执行以下sql查询:

Executing (default): SELECT `id`, `pattern`, `color`, `imageUrl`, `imageSource` FROM `images` AS `images` WHERE `images`.`pattern` = 'solid' AND `images`.`color` = 'navy-blue';

在我的本地数据库上测试工作并提供结果,但我似乎无法填充我的image对象,然后在我的视图中使用。我觉得我把它作为一个函数参数传递到了错误的地方,但是我不确定,我的console.log(image);没有回复。

router.get('/:pattern/:color/result', function(req, res, image){

    console.log(req.params.color);
    console.log(req.params.pattern);

    Images.findAll({ 
        where: {
            pattern: req.params.pattern,
            color: req.params.color
        },
        attributes: ['id', 'pattern', 'color', 'imageUrl', 'imageSource']
    }),
        console.log(image);
        //console.log(doc.descriptions_id);
        res.render('pages/result.hbs', {
            pattern : req.params.pattern,
            color : req.params.color,
            image : image
        })
});

这是我的模特:

var Sequelize      = require('sequelize');
var sequelize = new Sequelize('db', 'admin', 'test', {
    host: 'localhost',
    port: 3306,
    dialect: 'mysql'
});


var Images = sequelize.define('images', {
    pattern: {
        type: Sequelize.STRING,
        field: 'pattern'
    },
    color: {
        type: Sequelize.STRING,
        field: 'color'
    },
    imageUrl: {
        type: Sequelize.STRING,
        field: 'imageUrl'
    },
    imageSource: {
        type: Sequelize.STRING,
        field: 'imageSource'
    },
    description_id: {
        type: Sequelize.INTEGER,
        field: 'description_id'
    }
});

module.exports = Images;

1 个答案:

答案 0 :(得分:2)

你应该使用Promises

router.get('/:pattern/:color/result', function(req, res, image){
  console.log(req.params.color);
  console.log(req.params.pattern);

  Images.findAll({ 
    where: {
        pattern: req.params.pattern,
        color: req.params.color
    },
    attributes: ['id', 'pattern', 'color', 'imageUrl', 'imageSource']
  }).then(function(image){
    console.log(image);
    //console.log(doc.descriptions_id);
    res.render('pages/result.hbs', {
        pattern : req.params.pattern,
        color : req.params.color,
        image : image
    })
  });
});