问题
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