最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Using Asyncawait with mongoose - Stack Overflow

programmeradmin1浏览0评论

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: .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?

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./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?

Share Improve this question asked Nov 12, 2018 at 22:53 AlwaysblueAlwaysblue 12k44 gold badges141 silver badges253 bronze badges 4
  • 2 Not sure why the answer here was deleted or why there was so much back and forth mentary here, but the "warning" ( which is NOT an "error" ) es 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, and while the documentation "example" uses Bluebird, it's not exclusive to that library, but ANY Promise implementation. – Neil Lunn Commented Nov 12, 2018 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 google./… for the myriad of useful material with examples of what is wrong and how to correct it. – Neil Lunn Commented Nov 12, 2018 at 23:49
  • @NeilLunn Referring to this: stackoverflow./questions/51862570/… 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 github./StephenGrider/AdvancedNodeStarter the above code is from his blog route (github./StephenGrider/AdvancedNodeStarter/blob/master/routes/…) (you won't see the redis part in that route) – Alwaysblue Commented Nov 13, 2018 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 Commented Nov 13, 2018 at 12:11
Add a ment  | 

1 Answer 1

Reset to default 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);
  }
});
发布评论

评论列表(0)

  1. 暂无评论