3

I was taking this advance NodeJS course by Stephen Grinder where we were testing out caching in Redis.

As I run my application and reach the given route, I am thrown with this error

DeprecationWarning: Mongoose: mpromise (mongoose's default promise library) is deprecated, plug in your own promise library instead: http://mongoosejs.com/docs/promises.html

And other one which looks like this

UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1) [0] (node:11896) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code. [0] serving from MongoDb

Now, as mentioned, I went through and had a look at it very vaguely and it seems that their documentation does not talk about async and await.

This is the api route which is throwing the error

  app.get('/api/blogs', requireLogin, async (req, res) => {
    const redis = require('redis')
    const redisURL = 'redis://127.0.0.1:6379';
    const  client = redis.createClient(redisURL);
    const util = require('util')
    client.get = util.promisify(client.get)
    const cachedBlog = await client.get(req.user.id) 
    if (cachedBlog)  return res.send(JSON.parse(cachedBlogs))
    console.log("serving from MongoDb")
    const blogs = await Blog.find({_user: req.user.id})
    client.set(req.user.id, JSON.parse(blogs))
    res.send(blogs);
  });

To be specific this line here

 const blogs = await Blog.find({_user: req.user.id})

Where

const Blog = mongoose.model('Blog');

Note: To explain cache in a nutshell, Stephen Grinder have purposely set it inside a root.

[Question:] Can someone please tell me how can I use async/await (like what I have currently done inside the route) without being thrown any errors?

Alwaysblue
  • 9,948
  • 38
  • 121
  • 210
  • 2
    Not sure why the answer here was deleted or why there was so much back and forth commentary here, but the **"warning"** ( which is NOT an "error" ) comes from a lack of `mongoose.Promise = global.Promise` or similar setting. The *documentation reference* is further down the referenced page in the question [Plugging in your own Promises Library](https://mongoosejs.com/docs/promises.html#plugging-in-your-own-promises-library), and while the documentation "example" uses Bluebird, it's not exclusive to that library, but ANY Promise implementation. – Neil Lunn Nov 12 '18 at 23:47
  • 2
    The `UnhandledPromiseRejectionWarning:` on the other hand refers to your usage of `async/await` without specifically resolving the Promise inside a `try..catch` block. Hence the **WARNING** ( again, NOT an "error" ). But since you actually don't include that code in context in your question, we cannot "explicitly" tell you what to correct there, and can only be "generic" in reply. I kind of suggest https://www.google.com/search?q=async+await+UnhandledPromiseRejectionWarning for the myriad of useful material with examples of what is wrong and how to correct it. – Neil Lunn Nov 12 '18 at 23:49
  • @NeilLunn Referring to this: https://stackoverflow.com/questions/51862570/mongoose-why-we-make-mongoose-promise-global-promise-when-setting-a-mongoo/51862948#51862948 Don't we need to use `mongoose.Promise = global.Promise` when we are using bluebird? and it is no longer required? Additionally, Initially I am using Stephen Grinder Advance NodeJs boiler plate https://github.com/StephenGrider/AdvancedNodeStarter the above code is from his blog route (https://github.com/StephenGrider/AdvancedNodeStarter/blob/master/routes/blogRoutes.js) (you won't see the redis part in that route) – Alwaysblue Nov 13 '18 at 12:10
  • Please read it all again and the linked references. This has nothing to do with "bluebird" or any other incorrect answer which says otherwise. And again a "WARNING" is not an "error". – Neil Lunn Nov 13 '18 at 12:11

1 Answers1

6

Here there are two problems.

1: You did not set Promises for Mongoose. So set it.

mongoose.Promise = global.Promise

2: When you are using async/await then you need to wrap your code in try/catch block.

try { 

   // your code

} catch(e) {

  console.log(e);

}

In your case code should look like.

app.get('/api/blogs', requireLogin, async (req, res) => {
   try {
      const redis = require('redis')
      const redisURL = 'redis://127.0.0.1:6379';
      const  client = redis.createClient(redisURL);
      const util = require('util')
      client.get = util.promisify(client.get)
      const cachedBlog = await client.get(req.user.id) 
      if (cachedBlog)  return res.send(JSON.parse(cachedBlogs))
      console.log("serving from MongoDb")
      const blogs = await Blog.find({_user: req.user.id})
      client.set(req.user.id, JSON.parse(blogs))
      res.send(blogs);
  } catch(e) {
      console.log(e);
  }
});
Abhishek Singh
  • 1,631
  • 1
  • 17
  • 31
  • Shouldn't you use .exec() after calling the Mongoose "Blog.find()" function for it to execute? I'm new to async and a bit confused @AbhishekSingh – chopeds Oct 02 '19 at 08:11