Joao Jorge
Joao Jorge

Reputation: 103

How to manipulate a table with postgres without define a Sequelize Model

I have created a 'user' table directly in postgres shell, and all i need is to manipulate (CRUD) the data without have to create a model like this:

const User = sequelize.define('user', {
  firstName: {
    type: Sequelize.STRING,
  },
  lastName: {
    type: Sequelize.STRING,
  },
});

I've searched a lot in the documentation, but what I've seen so far, I must create a Model. Is there a way I can work without creating the Model?

Upvotes: 0

Views: 976

Answers (1)

Lin Du
Lin Du

Reputation: 102247

You can use Raw queries to manipulate the data without having to create a model.

For example:

We have User table in the database:

node-sequelize-examples=# select * from "User";
 UserId |          UserEmail           |                             UserAvatar                              
--------+------------------------------+---------------------------------------------------------------------
      1 | [email protected]          | https://s3.amazonaws.com/uifaces/faces/twitter/markretzloff/128.jpg
      2 | [email protected] | https://s3.amazonaws.com/uifaces/faces/twitter/faisalabid/128.jpg
      3 | [email protected]             | https://s3.amazonaws.com/uifaces/faces/twitter/sur4dye/128.jpg
(3 rows)

Use raw query to get all users:

import { sequelize } from '../../db';
import { QueryTypes } from 'sequelize';

sequelize.query('select * from "User"', { type: QueryTypes.SELECT }).then(console.log);

Logs:

Executing (default): select * from "User"
[ { UserId: 1,
    UserEmail: '[email protected]',
    UserAvatar:
     'https://s3.amazonaws.com/uifaces/faces/twitter/markretzloff/128.jpg' },
  { UserId: 2,
    UserEmail: '[email protected]',
    UserAvatar:
     'https://s3.amazonaws.com/uifaces/faces/twitter/faisalabid/128.jpg' },
  { UserId: 3,
    UserEmail: '[email protected]',
    UserAvatar:
     'https://s3.amazonaws.com/uifaces/faces/twitter/sur4dye/128.jpg' } ]

Upvotes: 2

Related Questions