SELECT sequelize

Asked

Viewed 348 times

0

I’m getting the error: (Node:20796) Unhandledpromiserejectionwarning: Typeerror: _Accessojs2.default.query is not a Function, I have the database configuration file:

import Sequelize from 'sequelize';

const dbConfig = new Sequelize('acessomfrc', 'USUARIO', 'SENHA', {
    host: '192.168.0.25',
    port: 5432,
    dialect: 'postgres',
    dialectOptions: {
        useUTC: false,
    }
});

export default dbConfig;

my file access.js:

import Sequelize from 'sequelize';
import dbConfig from '../db/config';

const acesso = dbConfig.define('acesso', {
    id: {
        type: Sequelize.INTEGER,
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
      },
      nome: {
        type: Sequelize.STRING,
        allowNull: false,
      },
      tag: {
        type: Sequelize.STRING,
        allowNull: false,
      },
      ultimoacesso: {
        type: Sequelize.STRING,
        allowNull: true,
      },
      status: {
        type: Sequelize.STRING,
        allowNull: false,
      },
      createdAt: {
        type: Sequelize.DATE,
        allowNull: false,
      },
      updatedAt: {
        type: Sequelize.DATE,
        allowNull: false,
      }
});

export default acesso;

the part to take the accesses:

const pegarAcessos = async (request, response) => {
    const acessos = await acesso.query("SELECT * FROM acesso");
    if(acessos) {
        response.send(200).send(acessos)
    }
    else {
        response.status(400).send({ error: 'Ocorreu algum erro.' })
    }
}

PS: I already tried to import dbconfig and replace: const acessos = await acesso.query("SELECT * FROM acesso") for const acessos = await dbConfig.query("SELECT * FROM acesso"); and I’ve also added the { type: dbConfig.QueryTypes.SELECT } or { type: acesso.QueryTypes.SELECT }, but when the error is not mentioned there on top of the message, when I step type: dbConfig.Query... I only get a return OK (without the answer), or passing acesso.Query... get the bug: (node:27588) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'SELECT' of undefined.

PS2: On another route, using the POST method and with files structured the same way, I have a create that works.

const adicionarTag = async (request, response) => {
    return await tag.create({
        tag: request.body.tag,
    }).then((tag) => {
        if (tag) {
            response.send(tag);
        } else {
            response.status(400).send({ error: 'Erro ao inserir.' });
        }
    });
};

1 answer

2


Your acesso is a model. Raw queries shall be made in a Sequelize. See the method documentation here and examples here.

const [results, metadata] = await sequelize.query("/* ... */");

Remember that it makes no sense to use a direct Raw query in the template because you will write the query entire, then you would still have to specify the table within the query; for this reason the method is present in Sequelize and not in Model’s :)

  • Thank you friend, but because by passing const accesses = await dbconfig.query("SELECT * FROM access", { type: dbconfig.QueryTypes.SELECT }); and by changing the if to: if(accesses) { Response.send(200). json(hits[0]) } get error: (Node:24992) Unhandledpromiserejectionwarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at Serverresponse.setHeader (_http_outgoing.js:526:11) where my route is: router.(authMiddleware); and router.get('/accesses', Controller.pegAccesss);

  • The name of the table in your bank is actually acesso? Isn’t it plural? Check it out. What’s more, for a SELECT * you can use a acesso.findAll() that makes more sense

  • 1

    Solved, it was using Sponse.send(200) instead of Sponse.status(200).send. Thanks.

  • Right. I still recommend using the acesso.findAll(). The ORM (in this case, Sequelize) is there for you to avoid using the most raw queries.

  • Thank you, Rafael!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.