使用node.js在mongodb中存储文件 [英] Storing a file in mongodb using node.js
问题描述
我需要使用node.js将文件存储在mongodb中,该文件放置在我的桌面中,我将不得不将其存储在mongodb数据库中.任何帮助将不胜感激
Hi i need to store a file in mongodb using node.js, the file is placed in my desktop i will have to store it in my mongodb database.I came across something called gridfs but am not sure how to proceed further.Any help will be much appreciated
推荐答案
虽然我不建议在Mongo中存储大文件,尽管有可能,较小的文件会更好.
While I don't recommend storing big files in Mongo, though it's possible, smaller files would be better.
仅读取文件的文本(如果是文本文件)或二进制文件(如果文件为二进制格式,即可执行文件).您可以使用fs
库读取文件并进行相应的编码.
Simply read the file's text (if it's a text file), or binary (if it's in a binary format i.e executable). You can use the fs
library to read the file and encode it accordingly.
然后将存储在变量中的数据插入数据库内部.
Then insert the data, stored in a variable, inside the database.
var fs = require('fs');
// Read file with proper encoding...
var data = //...
// Insert into Mongo
mongo.insert({file: data});
当您要从数据库中检索文件时,请执行相反的操作.根据文件类型的不同,编码/解码的过程也不同.
When you want to retrieve the file from the database, you'd do the opposite. The process of encoding/decoding is different depending on the type of file.
这篇关于使用node.js在mongodb中存储文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!