QwertyKing
QwertyKing

Reputation: 64

When using postgresql in Nodejs, how should I query the database from the webserver?

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

Upvotes: 0

Views: 1093

Answers (2)

Sombriks
Sombriks

Reputation: 3622

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!

Upvotes: 1

Smee
Smee

Reputation: 974

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.

Upvotes: 2

Related Questions