TypeError:count不是node.js和sequelize中的函数

时间:2018-04-19 10:45:28

标签: node.js express sequelize.js

我关注the Node.js + Express tutorial from the Mozilla Developer Network,但我使用MySQL sequelize

我在Model.count()电话上收到错误:

  

TypeError:Book.count不是函数      在bookCount(D:\ node-apps \ express-library \ controllers \ bookController.js:9:12)

以下是controllers/bookController.js的代码。错误是从行Book.count().then(callback);触发的。

var Book = require('../models/book');
var Author = require('../models/author');

var async = require('async');

exports.index = function(req, res) {
  async.parallel({
    bookCount: function(callback) {
      Book.count().then(callback);
    },
    authorCount: function(callback) {
      Author.count().then(callback);
    }
  }, function(err, results) {
    console.log(results);
    res.render('index', { title: 'Local Library', error: err, data: results });
  });
};

我调试console.log(Book)并返回[function]。以下是models/book.js

'use strict';

module.exports = (sequelize, DataTypes) => {
  var Book = sequelize.define('Book', {
    title: DataTypes.STRING,
    summary: DataTypes.STRING,
    isbn: DataTypes.STRING,
    url: DataTypes.STRING
  }, {});

  Book.associate = function(models) {
    // associations can be defined here
    Book.belongsTo(models.Author, {
      onDelete: 'CASCADE',
      foreignKey: {
        allowNull: false
      }
    });
    Book.hasMany(models.BookInstance);
    Book.belongsToMany(models.Genre, {
      through: 'BookGenres',
      onDelete: 'CASCADE'
    });
  };

  return Book;
};

3 个答案:

答案 0 :(得分:1)

在导出函数的models/book.js中,该函数返回Book模型,而不是模型本身。

所以当你写...

var Book = require('../models/book');

...你得到一个存储在Book变量中的函数。要获得模型本身,您应该运行该函数:

var Book = require('../models/book'); // that will be a function
var BookModel = Book(sequelize, dataTypes); // and that will be the model

或者您可以在require语句中运行该功能:

var Book = require('../models/book')(sequelize, dataTypes);
var Author = require('../models/author')(sequelize, dataTypes);

答案 1 :(得分:1)

您正在错误地导入续集模型。

            var Book = sequelize.import('../models/Book');
        //note that the 'sequelize' is instance of sequelize and not Constructor.

在您的情况下,您可能还希望匹配模型定义中的表名 '图书'而不是预订',因为您的模型定义定义了' Book'

参考 - http://docs.sequelizejs.com/manual/tutorial/models-definition.html#import

答案 2 :(得分:0)

我有这个模块脚本models/index.js

'use strict';

var fs        = require('fs');
var path      = require('path');
var Sequelize = require('sequelize');
var basename  = path.basename(__filename);
var env       = process.env.NODE_ENV || 'development';
var config    = require(__dirname + '/../config/config.js')[env];
var db        = {};

if (config.use_env_variable) {
  var sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  var sequelize = new Sequelize(config.database, config.username, config.password, config);
}

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    var model = sequelize['import'](path.join(__dirname, file));
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

所以,我替换了这两个需要的陈述

var Book = require('../models/book');
var Author = require('../models/author');

var models = require("../models");

然后,调用models.Book.count()models.Author.count()解决了问题。

var async = require('async');
var models = require('../models');

exports.index = function(req, res) {
  async.parallel({
    bookCount: function(callback) {
      models.Book.count().then(count => {
        callback(null, count);
      });
    },
    authorCount: function(callback) {
      models.Author.count().then(count => {
        callback(null, count);
      });
    }
  }, function(err, results) {
    res.render('index', { title: 'Local Library', error: err, data: results });
  });
};