0

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?

1
  • 1
    Don't name a table user. That wull cause trouble, since user is a reserved SQL keyword. Commented Oct 1, 2020 at 14:49

1 Answer 1

2

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' } ]
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much @slideshowp2, this is what I was looking for.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.