question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Problem to connect to mongodb - RateLimiterMongo

See original GitHub issue

Hi, I’m working on an open source project and node-rate-limiter-Flexible is a perfect library for the project.

As the project intends to deal with many connections and the budget for computational activity is low, I decided to connect the library through mongodb, in the free version (shared plan).

Well, my problem is that I can’t connect the library with mongodb at all, it always results in this error:

[nodemon] starting ts-node ./src/index.ts

(node:1758) [MONGODB DRIVER] Warning: Current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
(Use node --trace-warnings ... to show where the warning was created)

// The error
Error =>  Error: Mongo connection is not established
    at RateLimiterMongo._upsert (/Users/gustavo/Documents/dev/code/personal/projects/saskiabot/server/node_modules/rate-limiter-flexible/lib/RateLimiterMongo.js:117:29)
    at /Users/gustavo/Documents/dev/code/personal/projects/saskiabot/server/node_modules/rate-limiter-flexible/lib/RateLimiterStoreAbstract.js:203:12
    at new Promise (<anonymous>)
    at RateLimiterMongo.consume (/Users/gustavo/Documents/dev/code/personal/projects/saskiabot/server/node_modules/rate-limiter-flexible/lib/RateLimiterStoreAbstract.js:195:12)
    at rateLimiterMiddleware (/Users/gustavo/Documents/dev/code/personal/projects/saskiabot/server/src/index.ts:50:6)
    at Layer.handle [as handle_request] (/Users/gustavo/Documents/dev/code/personal/projects/saskiabot/server/node_modules/express/lib/router/layer.js:95:5)
    at trim_prefix (/Users/gustavo/Documents/dev/code/personal/projects/saskiabot/server/node_modules/express/lib/router/index.js:317:13)
    at /Users/gustavo/Documents/dev/code/personal/projects/saskiabot/server/node_modules/express/lib/router/index.js:284:7
    at Function.process_params (/Users/gustavo/Documents/dev/code/personal/projects/saskiabot/server/node_modules/express/lib/router/index.js:335:12)
    at next (/Users/gustavo/Documents/dev/code/personal/projects/saskiabot/server/node_modules/express/lib/router/index.js:275:10)

I wrote a simple code in ts (ready to use), just to demonstrate the problem:

// TypeScrip code
import express from "express";

import { RateLimiterMongo } from "rate-limiter-flexible";
import MongoClient from "mongodb";

const app = express();

const mongoOpts = {
  useNewUrlParser: true,
  reconnectTries: Number.MAX_VALUE,
  reconnectInterval: 100,
};

/**
 * I created this project in mongodb just to test this application, 
 * so I put the username and password here in the code just 
 * to make your testing simpler.
 * 
 * THIS IS NOT A PRODUCTION BD and will be disabled in the future 
 * when I manage to fix the problem.
 */

const db = {
  user: "test_admin",
  password: "Lc8vIC3WWXOBuMN9",
  dbname: "rate-limit",
};
const url = `mongodb+srv://${db.user}:${db.password}@testedb.bax1d.mongodb.net/${db.dbname}?retryWrites=true&w=majority`;

const mongoConn = MongoClient.connect(url, mongoOpts);

const opts = {
  storeClient: mongoConn,
  dbName: "rate-limit",
  points: 10, // 10 points
  duration: 60, // 60 seconds
};
const rateLimiterMiddleware = (
  req: express.Request,
  res: express.Response,
  next: express.NextFunction
) => {
  const userId = req.query.uid as string;

  if (!userId) {
    res.status(401).send("Unauthorized");
    return;
  }

  const rateLimiterMongo = new RateLimiterMongo(opts);
  rateLimiterMongo
    .consume(userId, 2) // consume 2 points
    .then((rateLimiterRes) => {
      console.log(`User ${userId} do a request`);
      next();
    })
    .catch((rateLimiterRes) => {
      console.log("Error => ", rateLimiterRes);
      res.status(429).send("Too Many Requests");
    });
};

app.use(rateLimiterMiddleware);

app.get("/", (req: express.Request, res: express.Response) => {
  res.send(`Hi user ${req.params.uid}!`);
});

const port = 3000;
app.listen(port, () => {
  console.log(`Server listening at http://localhost:${port}`);
});

If anyone can help me, I would be very grateful. Thanks.

Issue Analytics

  • State:closed
  • Created 2 years ago
  • Comments:6 (2 by maintainers)

github_iconTop GitHub Comments

1reaction
aquelegustavocommented, Jul 8, 2021

@animir That worked! My god, how did I not see this before?!

Thank you so much for your help ❤️!!

0reactions
animircommented, Jul 8, 2021

@gsmgg Hi, this line const rateLimiterMongo = new RateLimiterMongo(opts) should be moved out of the middleware. Rate limiter instance should be created once.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Cannot read property 'collection' of undefined with ... - GitHub
I'm implementing rate limit functionality with RateLimiterMongo and ... limiter config here and which nodejs library you use for MongoDB?
Read more >
Troubleshoot Connection Issues — MongoDB Atlas
This page outlines common connection issues and possible resolutions. To learn more about connecting to an Atlas cluster, see the Get Started with...
Read more >
Can't connect to mongodb.Could not connect to any servers in ...
while trying to connect with mongodb i'm getting this error : MongooseServerSelectionError: Could not connect to any servers in your MongoDB ...
Read more >
Unable to connect with node.js due to "mongodb+srv"
js parsing issue, specifically related to the “mongodb+srv”. (If I remove the + it gets past the error, but then of course doesn't...
Read more >
Error: couldn't connect to server 127.0.0.1:27017 - MongoDB
I'm following the install guide “Install MongoDB Community Edition on macOS”. I'm getting the following error: MongoDB shell version v4.2.3 ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found