【发布时间】:2022-01-29 20:59:45
【问题描述】:
我正在尝试使用 nextjs 中的 sequelize 从数据库中获取数据,模型创建成功,迁移也正常。 我正在构建端点,但似乎该功能未定义。 数据库中的表名是“users”
模型:user.js
"use strict";
const { Model } = require("sequelize");
// Fields to hide in the response
const PROTECTED_ATTRIBUTES = ["password", "token"];
module.exports = (sequelize, DataTypes) => {
class User extends Model {
toJSON() {
// hide protected fields
let attributes = Object.assign({}, this.get());
for (let a of PROTECTED_ATTRIBUTES) {
delete attributes[a];
}
return attributes;
}
static associate({ Category, Job, Application }) {
// define association here
this.hasMany(Category, { foreignKey: "userId", as: "categories" });
this.hasMany(Job, { foreignKey: "userId", as: "jobs" });
this.hasMany(Application, { foreignKey: "userId", as: "applications" });
}
}
User.init(
{
name: { type: DataTypes.STRING, allowNull: false },
surname: { type: DataTypes.STRING, allowNull: false },
email: { type: DataTypes.STRING, allowNull: false, unique: true },
password: { type: DataTypes.STRING, allowNull: false },
avatar: { type: DataTypes.STRING, allowNull: true },
role: { type: DataTypes.STRING, allowNull: false, defaultValue: 3 },
dob: { type: DataTypes.DATE, allowNull: false },
description: DataTypes.TEXT,
cv: DataTypes.TEXT,
},
{
sequelize,
modelName: "User",
}
);
return User;
};
api/test.js
const { User } = require("../../models");
export default function handler(req, res) {
// res.status(200).json({ name: "John Doe" });
const users = User.findAll({ limit: 10 }); //TypeError: Cannot read property 'findAll' of undefined
res.status(200).json({ users });
}
【问题讨论】:
标签: api express next.js sequelize.js backend