【问题标题】:Slow query with MongoDB Atlas and mongoose使用 MongoDB Atlas 和 mongoose 进行慢速查询
【发布时间】:2021-11-26 04:42:03
【问题描述】:

我有一个 MERN 应用程序,它使用 mongoose 连接到 MongoDB Atlas。虽然 Atlas 的平均响应时间小于 300 毫秒,但每隔一段时间就会超过 30 秒,一切都变得不可用。我想知道我处理与数据库的连接的方式是否有问题?

目前在我的app.js 文件中:

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

在我的routers.js 文件中,我处理如下路由:

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!')
    }
})

...

例如,上面的 Post 集合有 50 个文档,总大小为 2MB,但简单的 Post.find() 查询需要超过 30 秒才能完成。我还有其他四个类似的收藏;包括大小为 65MB 的图像集合。我查询数据库的方式有问题吗?

更新 1:

我已将所有图像移至云端,所以现在我的数据库只存储它们的 URL。然而,查询Post 集合仍需要大约 15 秒,该集合大小为 1.3MB,包含 50 个文档。万一错误的模式定义可能导致它,这里是它的模型:

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

【问题讨论】:

  • 可以添加Post数据模型吗?
  • @AminTaghikhani 是的 - 请查看我编辑的帖子

标签: node.js mongodb express mongoose mongodb-atlas


【解决方案1】:

将图像存储在 mongoDB 数据库中不是一个好习惯。

更好的方法是将图像存储在某些存储(例如 AWS S3)中,并将图像 URL 作为字符串保存在数据库中。

【讨论】:

  • 我已经完成了这项工作,并看到了一些改进 - 但 .find() 查询仍然需要大约 15 秒才能返回。是否存在其他问题?
【解决方案2】:

这个查询可能更快

await Post.find().lean(); 

注意如果你使用lea(),它会更快,因为 你得到纯 json 文档

但是你不能像这样修改文档

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 2020-06-25
    • 2018-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多