sequelize “findbyid” is not a function but apparently “findAll” is

▼魔方 西西 提交于 2020-05-11 03:54:05

问题


I am getting a very strange problem with sequelize, When I try to call the function findAll it works fine (same for create and destroy), but when I try to call function "findById", it throws "findById is not a function" (same for "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 model

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

回答1:


With Sequelize v5, findById() was replaced by findByPk(). Replace findById using findByPk and everything should work fine.




回答2:


the team of sequelize was deleting this function and replced it by a new function is

findByPk

like this

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



回答3:


Directly pass value.

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


来源:https://stackoverflow.com/questions/41577597/sequelize-findbyid-is-not-a-function-but-apparently-findall-is

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!