简体   繁体   中英

How to export and using sequelize models nodejs

This is my node model using sequelize:

`

"use strict";
const { Model } = require("sequelize");

module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    static associate(models) {
      User.hasMany(sequelize.models.Article, {
        foreignKey: "posts",
      });
    }
  }
  User.init(
    {
      firstName: DataTypes.STRING,
      lastName: DataTypes.STRING,
      age: DataTypes.STRING,
      email: DataTypes.STRING,
      password: DataTypes.STRING,
      type: DataTypes.STRING,
    },
    {
      sequelize,
      modelName: "User",
    }
  );
  return User;
};

but this error, but I'm not able to use the module in other files, I want to use it in the Service, and I'm imposing it like this: `


`const user = require("../models/user");

module.exports = {
  async listUsers(req, res) {
    const users = user.findAll();
    await console.log(user);
    res.send("okok");
    // const users = await User;
    // res.send(users);
  },
}`

`

this error says: TypeError: user.findAll is not a function``

Prescso usar o model em outros arquivos, acredito que estou importando incorretamene por ser uma função

You've made a typo when calling the function.

It's not

user.findAll();

but

User.findAll();

That's how you have defined the model, also make sure the import has the right uppercase.

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