javascript - 使用 Nodejs 在 mongodb 中存储文件

我将文件保存在服务器的 FS 上,现在我想将它们保存在 mongodb 中。(以便于备份和其他东西)。我想存储最大 4-5Mb 的文件,我尝试用 mongoose 保存它们使用 Buffer 类型。我成功保存并检索了它们,但是当我保存和检索 4 或 5Mb 等文件时,我注意到性能显着降低。

我的架构:

let fileSchema = new Schema({
name: {type: String, required: true},
_announcement: {type: Schema.Types.ObjectId, ref: 'Announcements'},
data: Buffer,
contentType: String
});

我如何从 expressjs 服务器中检索它们:

 let name = encodeURIComponent(file.name);
 res.writeHead(200, {
     'Content-Type': file.contentType,
     'Content-Disposition': 'attachment;filename*=UTF-8\'\'' + name
 });
 res.write(new Buffer(file.data));

我的问题是我是否应该使用一些 zlib 压缩函数(如“deflate”)在将缓冲区保存到 mongodb 之前对其进行压缩,然后在将二进制文件发送到客户端之前对其进行解压缩?这会让整个过程更快吗?我错过了什么吗?

最佳答案

您似乎正在尝试使用 mongoDb 保存大量信息。

我可以根据您的情况考虑 3 个不同的选项

云服务

  • 正如其他人已经在这里评论的那样,如果您要保存的文件是压缩文件,即使它是一个小文件,新的压缩也不会帮助您。 在这种情况下,我的建议是使用一些已经针对您尝试保存和检索的信息进行了优化的网络云服务,如果它是您可以使用的图像 Cloudinary它还提供免费服务,因此您可以对其进行测试。

本地存储和在数据库中保存路由

  • 其他解决方案可能是将编码数据存储在 .txt 文件中,将其存储在云端或文件系统中,然后仅将路由保存在数据库中。这样,您将不会依赖于 mongoDB 的速度来检索它,但您将有一个很好的方法来了解文件的位置。

使用 MongoDB 和 GridFS

  • 通过这种方式,您可以使用特定的方法在 MongoDB 中存储信息,当您处理 16mb 的文件时建议使用这种方法。 作为Official Documentation说:

Instead of storing a file in a single document, GridFS divides the file into parts, or chunks [1], and stores each chunk as a separate document. By default, GridFS uses a default chunk size of 255 kB; that is, GridFS divides a file into chunks of 255 kB with the exception of the last chunk.

接下来他们说在什么情况下你可以使用这种存储信息的方式:

In some situations, storing large files may be more efficient in a MongoDB database than on a system-level filesystem.

  • If your filesystem limits the number of files in a directory, you can use GridFS to store as many files as needed.
  • When you want to access information from portions of large files without having to load whole files into memory, you can use GridFS to recall sections of files without reading the entire file into memory.
  • When you want to keep your files and metadata automatically synced and deployed across a number of systems and facilities, you can use GridFS. When using geographically distributed replica sets, MongoDB can distribute files and their metadata automatically to a number of mongod instances and facilities.

希望它有用:)

https://stackoverflow.com/questions/45314066/

相关文章:

php - 如何单击表条目并在另一个 mongodb 集合(php/jquery)中搜索它

mongodb - 如何在 MongoDB 聚合框架中匹配 'undefined' 值?

mongodb - 如何从 Mongoose 中的对象 ID 获取创建日期?

mongodb - 如何在复杂的 Collection-Object 中附加新文档

java - Spring数据mongo在Query中使用OR

linux - 初始设置后 MongoDB 服务不会启动

mongodb - 为什么直接搜索 MongoDB 分片的全文搜索比通过集群管理器 (mongos)

node.js - 'this' 在 Mongoose 预保存 Hook 中未定义

javascript - MongoError : Unknown modifier: $pushA

mongodb - Mongod 服务启动退出,代码为 100