Alwaysblue
Alwaysblue

Reputation: 11940

Using Async/await with mongoose

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?

Upvotes: 3

Views: 5768

Answers (1)

Abhishek Singh
Abhishek Singh

Reputation: 1671

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);
  }
});

Upvotes: 6

Related Questions