Home > Mobile >  Slow query with MongoDB Atlas and mongoose
Slow query with MongoDB Atlas and mongoose

Time:10-06

I have a MERN app which uses mongoose to connect to MongoDB Atlas. While the average response time from Atlas is <300ms, every once a while this becomes >30 seconds and everything becomes unusable. I am wondering if something might be wrong with the way I handle connections to the database?

Currently in my app.js file:

mongoose.connect(`mongodb srv://<db name>:${process.env.DB_PASSWORD}@<...>.kea2z.mongodb.net/<...>?retryWrites=true&w=majority`, {useNewUrlParser: true, useUnifiedTopology: true})

In my routers.js file, I handle routes like the following:

import { Post } from './models.js'

...

const postRouter = express.Router()
postRouter.get('/', async (req, res) => {
    try {
        const posts = await Post.find()
        return res.json(posts)
    } catch(e) {
        console.log(`Error while indexing posts: ${e}`)
        return res.status(404).json('An error has occurred!')
    }
})

...

For instance, the above Post collection has 50 documents and 2MB total size, but the simple Post.find() query takes longer than 30 seconds to complete. I have four other collections similar to this; including a collection of images which has a size of 65MB. Is there a problem in the way I am querying the database?

CodePudding user response:

It's not a good practice to store images in a mongoDB database.

A better approach is to store the images in some storage (such as AWS S3) and save the image URLs in the database as a string.

CodePudding user response:

This Query may be faster

await Post.find().lean(); 

NOTICE if you use lean(), it is faster because you get pure json of document

but you cannot modify document like

 posts[0].name = "jack";
 await posts[0].save()

  • Related