简体   繁体   English

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

[英]Unable to select data from DB via Sequelize in Node.js

Why does the following code give me an error? 为什么以下代码给我一个错误?

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);
    });
  });
});

Output 输出量

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)

And here is the "dependencies" option from my package.json file: 这是我的package.json文件中的“ dependencies”选项:

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

The variable result in the callback should already be an array of results and not some object holding rows. 回调中的变量result应该已经是结果数组,而不是一些保存行的对象。 Changing it to this should get you the number of rows: 将其更改为此将获得行数:

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

Dump all of the data to see if it's actually the data you want. 转储所有数据以查看它是否确实是您想要的数据。

您的result没有rows属性。

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

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