【问题标题】:sequelize "findbyid" is not a function but apparently "findAll" is续集“findbyid”不是一个函数,但显然“findAll”是
【发布时间】:2017-05-25 11:02:33
【问题描述】:

我在使用 sequelize 时遇到了一个非常奇怪的问题,当我尝试调用函数 findAll 时它工作正常(创建和销毁相同),但是当我尝试调用函数“findById”时,它会抛出“findById is not a函数”(与“FindOne”相同)。

//works fine
var gammes = models.gamme.findAll().then(function(gammes) {
        res.render('admin/gammes/gestion_gamme',{
            layout: 'admin/layouts/structure' ,
            gammes : gammes,
            js: "gammes"
        });
    });

// throws models.gamme.findById is not a function
models.gamme.findById(req.params.id).then(function(gamme) {
        gamme.update({
            nom: req.body.nom
        }).then(function () {
            res.redirect("/gammes");
        })
    });

Gamme.js 模型

module.exports = function (sequelize, DataTypes) {
    "use strict";
    var gamme = sequelize.define('gamme', {
        id_gamme: {
            type: DataTypes.INTEGER.UNSIGNED,
            autoIncrement: true,
            primaryKey: true
        },
        nom: {
            type: DataTypes.STRING,
            allowNull: false
        }
    }, {
        classMethods: {},
        timestamps: false
    });
    return gamme;
};

【问题讨论】:

标签: node.js orm sequelize.js


【解决方案1】:

在 Sequelize v5 中,findById() 被 findByPk() 取代。使用 findByPk 替换 findById,一切正常。您可以找到查询文档here

【讨论】:

  • 是什么让您相信 OP 使用的是 v5?你看到关于安装版本是 v1.7 的评论了吗?
  • 我刚刚从 Sequelize 4.33.2 升级到 5.8.6,这解决了我的问题。
  • 我尝试在 sequelize 6.13.0 版本中,findByPk() 可以正常工作
【解决方案2】:

直接传值。

Question.findByPk(question_id).then(question => {
            return res.status(200).json({
                question: question
           });
}).catch(err => {
     console.log(err);
});

【讨论】:

    【解决方案3】:

    sequelize 团队正在删除这个函数并用一个新函数替换它

    findByPk

    喜欢这个

    // search for known ids
    Project.findByPk(123).then(project => {
      // project will be an instance of Project and stores the content of the table entry
      // with id 123. if such an entry is not defined you will get null
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 2020-04-08
      • 2017-04-24
      • 2019-11-17
      • 2018-05-12
      • 2019-12-20
      • 1970-01-01
      相关资源
      最近更新 更多