所以我在运行一个 node .带mongoose的js服务器,我一直在try download a large file using the GridFS node package,但我得到了以下错误:

MongoServerError:find命令::期间的执行器错误由::Sort引起,超出了104857600字节的内存限制,但未 Select 外部排序.

以下是我用来下载文件的代码:

// Stream a single file. 
router.get('/stream/:filename', async function(req, res, next){
    try{        
        const file = gfs.find({
            filename: req.params.filename
        }).toArray((err, files) => {
        if (!files || files.length === 0) {
            return res.status(404)
            .json({
                err: "no files exist"
            });
        }

        gfs.openDownloadStreamByName(req.params.filename)
            .pipe(res);
        });
    }catch(err){
        return res.status(400).json({
            err:'Could not fetch the file.'
        })
    }
}); 

考虑到这it's OK to answer your own question on StackOverflow个问题,我想记录下这个问题,以便我的解决方案可以帮助以后遇到它的其他人.

推荐答案

事实证明,当你用GridFS流媒体下载文件时,组成文件的文档会被排序.根据this blog post,当进行排序时,MongoDB first attempts to retrieve the documents using the order specified in an index.当没有可用的索引时,它会try 将文档加载到内存中并在那里排序.

问题是,Mongo默认配置为在超过32MB的使用率时中止操作.这就是我们遇到上述"排序超出内存限制"错误的原因.为了解决这个问题,你需要下载you’ll have to create an index for the ‘n’ field that contains the order of the file chunks个.为此,您可以直接通过数据库界面(我使用MongoDB Compass GUI)创建索引,也可以使用createIndex()方法通过代码创建索引:

// Create an index for the 'n' field to help sort the chunks collection.
db.collection('files.chunks').createIndex({n: 1});

Node.js相关问答推荐

一个函数中的两个依赖的NodeJS数据库操作.如果第二个失败了怎么办?

如何修复node.js中的错误代码无法加载资源:服务器响应状态为403(禁止)

Node fetch 实现似乎与 Deno 和 Bun 不同,导致网站没有返回响应?

有没有办法判断 UUID 是否是使用 node.js 中的特定命名空间生成的?

找不到react 模块:错误:默认条件应该是最后一个

如何在mongodb中获取对象数组内部的数据

ResponseError:键空间ks1不存在

npm install 在 Mac 上的 Node-gyp 构建错误

为什么我的 Cypress Post 请求的请求正文是空的?

在 nodejs 中使用 multer 上传文件返回未定义的 req.file 和空的 req.body

用户与mongoose 的完美搭配

如何更新 MongoDB 中对象数组中的键?

使用 mongoose 查找过go 7 天的注册用户总数

为什么我在生产环境中 deproy Next.js 示例项目时 CSS 不起作用?

Ansible 将以什么用户身份运行我的命令?

适用于 Windows 7 的 NodeJS

用一级 try ... catch 捕获 JavaScript Promise 中的错误

Nodejs续集批量更新

如何在 node.js 沙箱中安全地运行用户提交的脚本?

Puppeteer 等待所有图像加载然后截图