javascript - 放置 mongodb 查询时,总 JS 堆大小增加约 120MB
问题描述
我不明白为什么当我在控制器的函数中放置 mongodb 数据库查询时堆大小不断增加。
这是我的路由器
import { Router } from "express";
import profileController from '../controllers/profileController';
class userRouter {
public router: Router;
constructor() {
this.getRoutes();
}
getRoutes() {
this.router.get("/profile-list", profileController.getProfileList);
}
}
export default new userRouter().router;
这是我的控制器
import Profile from "../models/profile";
export class profileController {
static async getProfileList(req: any, res: any, next: any) {
try {
const getList = await Profile.find();
res.status(200).json({
status: 200,
message: "Success",
data: getList,
});
} catch (error) {
console.log(error);
}
}
}
这是我的模型
import * as mongoose from "mongoose";
import { model } from "mongoose";
const profileSchema = new mongoose.Schema({
userId: { type: String, required: true },
name: { type: String, default: ""},
},
{ timestamps: true }
);
export default model("profile", profileSchema);
没有 getProfileList 函数的总堆大小 => 135 MB
放置 getProfileList 函数后的总堆大小 => 255 MB(特别是放置 const getList = await Profile.find(); 后)
在这里,我检查了内存,并在比较中发现了这一点:
TypeObject 从 3MB 增加到 99MB(数组)从 26MB 增加到 88MB
请任何人帮助我理解为什么会这样?还是在这种情况下通常。
解决方案
问题是您没有使用任何限制,因此 usingawait Profile.find();
将返回数据库中的所有文档,因此当您调用控制器时,它将返回数据库中的所有数据,这些数据会大大增加堆大小。
您可以使用limit
andskip
为您的端点实现分页。
此外,您还应该考虑必须将Mongoose
库加载到您的内存中、与数据库的连接等等,这也需要 RAM。
推荐阅读
- javascript - 根据javascript中的变量值定义对象字段名称
- node.js - 用玩笑测试 node.js:无法窥探保存属性,因为它不是函数
- android - 无法在图像视图 Android Studio 中加载可绘制对象
- pdf - 有没有办法在命令行中使用完整的文件路径而不输入它?
- php - 如何修改json键
- amazon-web-services - AWS:从请求者 VPC 中的 Fargate 任务连接到接受者 VPC 中的 VPC 端点
- javascript - 在 React 中推送到导入的数组时出现奇怪的行为
- android - Android 自定义 SQLite 加密
- differential-equations - 管道温度计算的隐式欧拉方法显示振荡
- javascript - 使用 Express 部署时出现 Firebase 功能错误