0

Currently I am using the pg module. I know how to query the database

client.query("INSERT INTO users(username, password) values($1, $2)", [username, password]

But I was wondering if there's a separate module that I don't know about or a "good practice" way of doing queries with PostgreSQL on Node. Especially if there is a primary key such as a username. I tried building models such as User.js but in the models I am still hard coding the query.

Thanks

3
  • Possible duplicate of What is the proper way to use the node.js postgresql module? Commented Mar 24, 2016 at 11:48
  • That is not what I am looking for. I already know how to do those things. Commented Mar 24, 2016 at 14:15
  • Have you seen pg-promise? That has everything, including the best way to maintain your external SQL. Commented Mar 24, 2016 at 15:27

2 Answers 2

2

I think a much easier way of doing this is to use something like Sequelize ORM. In a nutshell, Sequelize will allow you to write all of your schemas and queries using JS objects. If you're unfamiliar with it, there are a few great examples here.

Basically, this will abstract a lot of the raw query code from your Node.js module, and allow you to write more syntactic JS to interact with your DB. It also includes promises, which will give you an easier way around the async nature of Node rather than queries nested inside each other.

Sign up to request clarification or add additional context in comments.

Comments

1

If what you want is to gain any level of abstraction for your data layer, knex/bookshelf is what you want.

The best part is you can choose which level of abstraction you want.

Want/need to do raw sql queries? knex can do that for you.

Want neat query builder capabilities? knes have that too.

In need of industrial ORM lift? there is bookshelf.

Bonus: knex has a very decent migration tool, which means if you want to manage database schema versions you can do that too! Migration tools are the best way to avoid madness when dealing with real world databases.

Give it a try:

http://knexjs.org/

http://bookshelfjs.org/

Hope it helps you as it helps me!

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.