猫鼬的NodeJs api任何请求都可以高效地转到另一个集合 [英] NodeJs api with mongoose any request go to another collection efficient

查看:54
本文介绍了猫鼬的NodeJs api任何请求都可以高效地转到另一个集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与用户一起编写用于应用程序的nodeJs api,我希望每个用户都使用另一个mongo集合.

I'm write nodeJs api for app with users and I want for each user to use another mongo collection.

我用params字段中的URL地址识别每个用户.一切都很好.但是当我动态地进行收集时,速度非常慢.

I recognize each user with the URL address in the params fields. everything is work fine. But when I go to collection dynamically it's very slow.

有谁知道如何更快地做到这一点?

any one idea how to do this faster?

先谢谢;)

app.js

此代码在2.5秒内完成

this code do req in 2.5 seconds

POST /login 200 2487.531 ms - 206

    app.use("/:businessUrl", (req, res, next) => {
  console.log(req.params.businessUrl);
   mongoose
  .connect(process.env.MONGO_URI + `${req.params.businessUrl}retryWrites=true&w=majority`,)
    .then((result) => {
      console.log("DB Connected");
      next();
    })
    .catch((err) => {
      return next(err);
    });
});

,并且在对集合进行硬编码时使用此代码在0.5秒内完成相同的请求

and this code when the collection is hard coded do the same req in 0.5 seconds

POST /login 200 461.829 ms - 206

 mongoose .connect(process.env.MONGO_URI + `businessUrl?retryWrites=true&w=majority`)
  .then((result) => {
    console.log("DB Connected");
  })
  .catch((err) => {});

推荐答案

等待时间即将到来,因为每次API被点击时您都在创建连接.

The latency is coming because you are creating a connection everytime the API is being hit.

从实现中可以看到,您正在使用同一台服务器,只是在切换数据库.

As I can see from implementation, There is same server that you are using just switching the database.

因此,您可以使用mongoose提供的 useDB 方法.它还具有为每个数据库的连接对象维护高速缓存的选项.官方文档: https://mongoosejs.com/docs/api/connection.html#connection_Connection-useDb

So, You can use the useDB method provided by mongoose. It also has an option to maintain cache for the connection object for each DB. Official Docs: https://mongoosejs.com/docs/api/connection.html#connection_Connection-useDb

使用上述方法只会在首次访问API时创建与数据库的连接,但是如果我们在第一次访问API时会从缓存中解析它.

Using above approach will only create connection to the database when the API is being hit first time but will resolve it from cache if we are hitting it after first time.

这篇关于猫鼬的NodeJs api任何请求都可以高效地转到另一个集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆