NodeJs api with mongoose any request go to another collection efficient

主宰稳场 提交于 2021-01-29 15:15:20

问题


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

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?

thanks in advance ;)

app.js

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

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

回答1:


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.

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

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.



来源:https://stackoverflow.com/questions/61911690/nodejs-api-with-mongoose-any-request-go-to-another-collection-efficient

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!