简体   繁体   中英

Slow query with MongoDB Atlas and mongoose

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?

UPDATE 1:

I have moved all the images to the cloud so now my database only stores their URLs. However it still takes ~15s for the Post collection to be queried, which has a size of 1.3MB and contains 50 documents. In case a faulty schema definition may be causing it, here is its model:

const Post = mongoose.model('Post', new mongoose.Schema({
    slug: String,
    title: String,
    authors: [String],
    date: Date,
    categories: [String],
    content: String
}))

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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM