无法通过Node.js中的Sequelize从DB中选择数据

时间:2015-11-16 13:18:00

标签: javascript node.js orm sequelize.js

为什么下面的代码会给我一个错误?

var Sequelize = require('sequelize');
var sequelize = new Sequelize('schema', 'root', '');
var Foo = sequelize.define('Foo', {
  name: Sequelize.STRING
});
sequelize.sync().then(function() {
  Foo.create({
    name: 'some name'
  }).then(function() {
    Foo.findAll({ where: { name: { $like: '%s%' } } }).then(function(result) {
      console.log(result.rows.length);
    });
  });
});

输出

Executing (default): SELECT `id`, `name`, `createdAt`, `updatedAt` FROM `Foos` AS `Foo` WHERE `Foo`.`name` LIKE '%s%';
Unhandled rejection TypeError: Cannot read property 'length' of undefined
    at null.<anonymous> (E:\work\projects\src\preorders\server.js:13:30)
    at tryCatcher (E:\work\projects\src\preorders\node_modules\sequelize\node_modules\bluebird\js\main\util.js:26:23)
    at Promise._settlePromiseFromHandler (E:\work\projects\src\preorders\node_modules\sequelize\node_modules\bluebird\js\main\promise.js:507:31)
    at Promise._settlePromiseAt (E:\work\projects\src\preorders\node_modules\sequelize\node_modules\bluebird\js\main\promise.js:581:18)
    at Promise._settlePromises (E:\work\projects\src\preorders\node_modules\sequelize\node_modules\bluebird\js\main\promise.js:697:14)
    at Async._drainQueue (E:\work\projects\src\preorders\node_modules\sequelize\node_modules\bluebird\js\main\async.js:123:16)
    at Async._drainQueues (E:\work\projects\src\preorders\node_modules\sequelize\node_modules\bluebird\js\main\async.js:133:10)
    at Async.drainQueues (E:\work\projects\src\preorders\node_modules\sequelize\node_modules\bluebird\js\main\async.js:15:14)
    at process._tickCallback (node.js:419:13)

这是&#34;依赖&#34;我的package.json文件中的选项:

  "dependencies": {
    "mysql": "^2.9.0",
    "sequelize": "^3.13.0"
  }

2 个答案:

答案 0 :(得分:1)

回调中的变量result应该已经是一个结果数组,而不是一些持有行的对象。将其更改为此应该可以获得行数:

Foo.findAll({ where: { name: { $like: '%s%' } } }).then(function(result) {
  console.log(result.length);
});

转储所有数据以查看它实际上是否是您想要的数据。

答案 1 :(得分:-1)

您的//offers/offer[@id=(//item[@attr="value1"]/@id)]/elem/text()没有result属性。