Lin Du
Lin Du

Reputation: 102447

What is the same function in postgres as mongoose middleware?

Here is the link about mongoose middleware: https://mongoosejs.com/docs/middleware.html

My case is I want to update some fields after a SQL query from database when client user send request to call my api. And the fields which need to be updated is based on Date, so they will be updated frequently.

Update these fields in the initialization of my application is not enough.

With mongoose, I can use below way:

schema.post('findOne', function(doc, next) {
  const doc = updateFields(doc);
  doc
    .save()
    .then(() => next())
    .catch(next);
})

How can I do this using postgresql?

I find a way but it seems duplicated.

The way is using UPDATE and RETURNING. But I have to write this SQL everywhere.

Or, I can encapsulate a method and call it firstly when need update the fields? I think it's duplicated either.

So, what's the best way for my case? thanks.

Upvotes: 0

Views: 278

Answers (1)

Design correctly your database schema (and be sure to have appropriate database indexes, and be aware of database normalization). Then explicit the set of SQL requests your application should make.

You might be interested by triggers (which looks similar to what you call "middleware")

Most of the requests would be in prepared statements, using PQprepare in the initialization of your application.

Be aware that MongoDB is a NoSQL database, but PostGreSQL is a relational database, so they require different mindsets and approaches and should be used differently.

Upvotes: 1

Related Questions