如何将文件保存到 MongoDB?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13907509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:57:24  来源:igfitidea点击:

How do I save a file to MongoDB?

mongodbfile-upload

提问by paulmelnikow

I want to save a user selected file to MongoDB. How do I correctly add the file to the BSON object in order to add it to MongoDB? If my approach is incorrect please point in the right direction.

我想将用户选择的文件保存到 MongoDB。如何将文件正确添加到 BSON 对象以便将其添加到 MongoDB?如果我的方法不正确,请指出正确的方向。

Below is the client code. This jQuery functions gathers the text (need help on the file part) on every input field and sends it to the server as a BSON object.

下面是客户端代码。这个 jQuery 函数收集每个输入字段上的文本(需要文件部分的帮助),并将其作为 BSON 对象发送到服务器。

$('#add').click(function()
            {
                console.log('Creating JSON object...');
                var classCode = $('#classCode').val();
                var professor = $('#professor').val();
                var description = $('#description').val();
                var file = $('#file').val();

                var document = 
                {
                    'classCode':classCode,
                    'professor':professor,
                    'description':description,
                    'file':file,
                    'dateUploaded':new Date(),
                    'rating':0 
                };
                console.log('Adding document.');
                socket.emit('addDocument', document);
            });

The HTML of the form:

表单的 HTML:

   <form>
        <input type = 'text' placeholder = 'Class code' id = 'classCode'/>
        <input type = 'text' placeholder = 'Document description' id = 'description'/>
        <input type = 'text' placeholder = 'Professor' id = 'professor'/>
        <input type = 'file' id = 'file'/>
        <input type = 'submit' id = 'add'/>
    </form>

The server side code in CoffeeScript:

CoffeeScript 中的服务器端代码:

#Uploads a document to the server. documentData is sent via javascript from submit.html
            socket.on 'addDocument', (documentData) ->
                console.log 'Adding document: ' + documentData
                db.collection 'documents', (err, collection) ->
                    collection.insert documentData, safe:false
                    return

采纳答案by Sergey Gavruk

To store files in MongoDB you should try to use GridFS
You can find some tutorials about working with GridFS (example).
Check your MongoDB Driver's API and try to implement it in your project

要将文件存储在 MongoDB 中,您应该尝试使用GridFS
您可以找到一些有关使用GridFS 的教程(示例)。
检查您的 MongoDB Driver 的 API 并尝试在您的项目中实现它

回答by paulmelnikow

If your files are small enough(under 16 megabytes), instead of adding the complexity of GridFS, you can just embed the files into BSON documents.

如果您的文件足够小(小于 16 兆字节),您可以将文件嵌入到 BSON 文档中,而不是增加 GridFS 的复杂性。

BSON has a binary data type, to which any of the drivers should provide access.

BSON 具有二进制数据类型,任何驱动程序都应提供访问权限。

If your file is a text file you can just store it as a UTF8 string.

如果您的文件是文本文件,您可以将其存储为 UTF8 字符串。

回答by Rémi Becheras

When to Use GridFS

何时使用 GridFS

From official doc: https://docs.mongodb.com/manual/core/gridfs/#when-to-use-gridfs

来自官方文档:https: //docs.mongodb.com/manual/core/gridfs/#when-to-use-gridfs

In MongoDB, use GridFS for storing files larger than 16 MB.

在 MongoDB 中,使用 GridFS 存储大于 16 MB 的文件。

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

在某些情况下,在 MongoDB 数据库中存储大文件可能比在系统级文件系统中更有效。

  • 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.

  • 如果您的文件系统限制了目录中的文件数量,您可以使用 GridFS 存储所需数量的文件。

  • 当您想从大文件的部分访问信息而不必将整个文件加载到内存中时,您可以使用 GridFS 来调用文件的各个部分,而无需将整个文件读入内存。

  • 当您希望让您的文件和元数据在多个系统和设施之间自动同步和部署时,您可以使用 GridFS。使用地理分布式副本集时,MongoDB 可以自动将文件及其元数据分发到多个 mongod 实例和设施。

Do not use GridFS if you need to update the content of the entire file atomically. As an alternative you can store multiple versions of each file and specify the current version of the file in the metadata. You can update the metadata field that indicates “latest” status in an atomic update after uploading the new version of the file, and later remove previous versions if needed.

如果您需要以原子方式更新整个文件的内容,请不要使用 GridFS。作为替代方案,您可以存储每个文件的多个版本并在元数据中指定文件的当前版本。您可以在上传文件的新版本后更新原子更新中指示“最新”状态的元数据字段,然后根据需要删除以前的版本。

Furthermore, if your files are all smaller the 16 MB BSON Document Size limit, consider storing the file manually within a single document instead of using GridFS. You may use the BinData data type to store the binary data. See your drivers documentation for details on using BinData.

此外,如果您的文件都小于 16 MB BSON 文档大小限制,请考虑将文件手动存储在单个文档中,而不是使用 GridFS。您可以使用 BinData 数据类型来存储二进制数据。有关使用 BinData 的详细信息,请参阅您的驱动程序文档。