简体   繁体   中英

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:

  "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. 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属性。

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