0

I've been working with mongoDB in node using mongoose. The following query to mongoose is made when a GET request is made to a route (e.g. localhost:7000/restaurants) and displays an array full of matching objects

async func() {
    return this.Restaurants.find({$or: [{city: somecity}, {postal_code: somepostalcode}]}).then(result => {
        return result;
    })
}

I tried a similar thing using postgres, however, calling it returns nothing on the browser, but is successfully logged onto the console:

async func(){
    return await client.query(`SELECT * FROM restaurants WHERE city = '${somecity}' OR postal_code = '${somepostalcode}';`, (err, res) => {
        console.log(res.rows);
        return res.rows;
    })
}

Why does this happen, if they both seem to return the same type of object? Is there a way to make the postgres result visible?

Thank you for the help!

2
  • Not too sure about PostgreSQL but your query statement seems off ... its probably trying to query city ='somecity' or postal_code:'somepostalcode' literally. SELECT * FROM restaurants WHERE city = '${somecity}' OR postal_code = '${somepostalcode}'; Or follow their guide client.query(<query>,<value>,<callback>) Commented Feb 16, 2021 at 2:11
  • Oh, I copied it wrong. Thanks for the heads up! However I'm still getting the issue (result gets logged onto console, but nothing is outputted to the browser) Commented Feb 16, 2021 at 8:09

1 Answer 1

1

It is most probably because postgres API is callback based. You would need to wrap callback in promise and return query response in resolve. Updating code to something like below should help:

async func(){
  return new Promise((resolve, reject) => {
    client.query(`SELECT * FROM restaurants WHERE city = '${somecity}' OR postal_code = '${somepostalcode}';`, (err, res) => {
      if(err) {
        return reject(err)
      }
      
      return resolve(res.rows);
    })
  })
}
Sign up to request clarification or add additional context in comments.

Comments

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.