3

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

Amanda G
  • 1,931
  • 10
  • 33
  • 43
  • similiar to: http://stackoverflow.com/questions/10092282/saving-files-to-mongodb-gridfs-with-node-js.. BTW: @Daniel's answer doesn't touch upon GridFS, which IS suited for large objects. – Geert-Jan Dec 24 '12 at 11:35

2 Answers2

4

If your file size exceeds 16Mb, Mongo's maximum document size, you must use gridFS if you wish to store the files in your DB.

There's a very useful run down of the reasons to use gridFS here: http://docs.mongodb.org/manual/faq/developers/#faq-developers-when-to-use-gridfs

In terms of implementation in node (if using the nativ mongo driver):

var  mongodb = require('mongodb')
   , MongoClient = mongodb.MongoClient
   , Grid = mongodb.Grid //use Grid via the native mongodb driver
   ;

Once you've setup you connection, when it comes to writing the file into gridFs

var grid = new Grid(db, 'fs'); //db being a handle to your database

var buffer = //read the file in to a buffer

//write the buffer out to mongo
grid.put(buffer, {metadata:{category:'text'}, content_type: 'text'}, function(err, fileInfo) {
 if(err) {
   //handle any errors here
 }
});
Rob Squires
  • 2,108
  • 16
  • 15
2

While I don't recommend storing big files in Mongo, though it's possible, smaller files would be better.

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.

Daniel
  • 1,692
  • 2
  • 13
  • 19
  • fs will read the contents of the file but my requirement is to store the entire file say name.txt as it is into my mongodb. Do you have any idea? – Amanda G Dec 24 '12 at 07:10
  • @AmandaG You can't store a file, as is, in a database. That's what a filesystem is for. You'd instead, store the contents of the file in the database. – Daniel Dec 24 '12 at 07:31
  • @AmandaG You can have a simple collection: `files` that have a `filename` and `contents` key that would "replicate" the same effect as having it within a filesystem (sorta) – Daniel Dec 24 '12 at 07:33
  • :I stored the file contents into a variable and saved the variable into the mongodb ie data but when i tried retrieving i got the following output requestParam: '[object Object]' i did not get the data i stored.Any idea regarding this will be really helpful – Amanda G Dec 26 '12 at 05:24