Nodejs Express API-猫鼬的性能响应(慢)

时间:2020-11-06 11:25:24

标签: node.js mongodb api express mongoose

我对mongoose find()请求的响应时间很慢(仅4300个文档),我的mongodb服务器安装在Google Compute Engine(具有4个内核和16 GB内存的Ubuntu VM)中,这是我的get函数:

getBooks = async (req, res) => {
    await Book.find({}, (err, books) => {
        if (err) {
            return res.status(400).json({ success: false, error: err })
        }
        if (!books.length) {
            return res
                .status(404)
                .json({ success: false, error: `books not found` })
        }
        return res.status(200).json({ success: true, data: books})
    })
}

这需要 16.89 秒!

这是.explain(“ executionStats”)的结果:

{
    "success": true,
    "data": [
        {
            "queryPlanner": {
                "plannerVersion": 1,
                "namespace": "Library.Books",
                "indexFilterSet": false,
                "parsedQuery": {},
                "winningPlan": {
                    "stage": "COLLSCAN",
                    "direction": "forward"
                },
                "rejectedPlans": []
            },
            "executionStats": {
                "executionSuccess": true,
                "nReturned": 4319,
                "executionTimeMillis": 1,
                "totalKeysExamined": 0,
                "totalDocsExamined": 4319,
                "executionStages": {
                    "stage": "COLLSCAN",
                    "nReturned": 4319,
                    "executionTimeMillisEstimate": 0,
                    "works": 4321,
                    "advanced": 4319,
                    "needTime": 1,
                    "needYield": 0,
                    "saveState": 33,
                    "restoreState": 33,
                    "isEOF": 1,
                    "invalidates": 0,
                    "direction": "forward",
                    "docsExamined": 4319
                },
                "allPlansExecution": []
            },
            "serverInfo": {
                "host": "mongodb-vm",
                "port": 27017,
                "version": "3.6.3",
                "gitVersion": ""
            },
            "ok": 1
        }
    ]
}

我添加了lean()函数并将查询更改为:

getBooks = async (req, res) => {
    await Book.find({})
        .lean()
        .exec(function (err, books) {
            if (err) {
                return res.status(400).json({ success: false, error: err })
            }
            if (!books.length) {
                return res
                    .status(404)
                    .json({ success: false, error: `Books not found` })
            }
            return res.status(200).json({ success: true, data: books})
        });
}

响应时间已变成: 9.01 秒..仍然很慢!

谢谢

编辑1

使用lean():

  1. 在Postaman上我的计算机本地主机测试中:9到15秒之间
  2. 在Postaman上Google App Engine测试中部署的相同API(实例为F4_1G):2.58秒

0 个答案:

没有答案