【发布时间】:2021-02-21 16:12:40
【问题描述】:
我有一个用 mongoose 设置的 mongo db。我正在尝试使用 sort 在 10 年代将它们显示在仪表板上,但在检查 140 左右时,我得到 MongoError: Sort operation used more than the maximum 33554432 bytes of RAM.
我正在尝试添加一个索引来保持性能,但似乎有些东西不起作用。
这是架构。
const InspectionSchema = new Schema(
{
inspectionId: {
type: Schema.Types.String,
required: true,
unique: true,
},
inspector: {
type: Schema.Types.ObjectId,
ref: 'users',
required: true,
},
inspectorName: {
type: Schema.Types.String,
},
status: {
type: Schema.Types.String,
enum: statuses,
default: STATUS.IN_PROGRESS.value,
required: true,
},
archived: {
type: Schema.Types.Boolean,
default: false,
},
data: {
type: Schema.Types.Mixed,
required: true,
},
report: {
type: Schema.Types.Mixed,
required: true,
},
},
{ timestamps: true }
);
然后这是我的排序调用:
.limit(parseInt(query.limit))
.skip(query.limit * query.page)
.sort({
createdAt: 'desc',
})
.then((inspections) => {
return res.json({
success: true,
count,
inspections: inspections.map((inspection) => ({
...inspection.toObject(),
inspector: inspection.report.inspector,
})),
});
})
.catch((err) => {
console.log(err);
return res.status(500).json({
success: false,
});
});
query.limit 通常为 10,查询页面是仪表板上显示它们的页码。
它通常会达到大约 140 次检查的内存限制。 mongoose 在 createdAt 和 _id 中添加。认为 _id 将是我尝试过的索引:
BoundInspection.find(filter)
.limit(parseInt(query.limit))
.skip(query.limit * query.page)
.sort({
_id: -1,
createdAt: 'desc',
})
.then((inspections) => {
return res.json({
success: true,
count,
inspections: inspections.map((inspection) => ({
...inspection.toObject(),
inspector: inspection.report.inspector,
})),
});
})
.catch((err) => {
console.log(err);
return res.status(500).json({
success: false,
});
});
但它仍然在同一个地方遇到同样的错误。 任何帮助将不胜感激。
【问题讨论】:
-
当您运行索引 + 字段等组合时,情况会发生变化。恕我直言,您应该创建一个可以在查询中使用的索引。 createdAt 是 NumberOfDocs/10 或 /20 可以工作的。
_id+createdAt也可能有效。
标签: node.js mongodb mongoose mongodb-query mongoose-schema