3

I am new to mongodb.

I stored binary data with below code snippet:

var data = fs.readFileSync(path);
  var image = new mongodb.Binary(data);
  //open connection/collection
var record = {picname: id, content: image   };
collection.save(record, {safe: true}, function(err,result){
  if(err)
  console.log(err.stack);
  });//save

I can see the record size in db. there is binary data. record size also matched with file size. am happy.

Now, retrieved same binary data from mongo and trying to send it in response:

var record = {picname: id};
  collection.findOne(record, function(err,result){
    if(err)
    console.log(err.stack);
    else
    {
    console.log('before read from db for download.');
    //HOW TO READ IMAGE/BINARY DATA FROM RESULT?
                                               //I need to send result in response. Any Idea?
    console.log('before read from db for download');
    }
    });

I am sending binary data with below code snippet. It's not working for all the files. What could be the issue:

collection.findOne(record, function(err,result){
                if(err)
                    console.log(err.stack);
                else
                {
                    console.log('before read from db for download. result: [' + result.picname + " ], type: " + result.imagetype);
                    res.end(result.content.buffer, "binary");
                    console.log('Responded SUCCESS: ' + id );
                }
            });//findOne

Please let me know how to retrieve and send via response.

Thanks in advance DD.

6
  • You said "It's not working for all the files". Which files does it work for and which does it not work for; is there a pattern? Also, how isn't it working? Do you get an error, is the file corrupted , etc.? Commented Sep 2, 2014 at 16:49
  • Noticed gif not working for sometimes. Commented Sep 2, 2014 at 18:34
  • Consider to use GridFS, after that you'll be able to write with the following way: file.stream(true).pipe(res); Commented Sep 3, 2014 at 5:09
  • Storing images in Mongodb. Not on GridFS. Storing binary data into Mongodb. Fetching binary data from Mongodb by findOne. Should I use GridFS for less than 4MB images. Please suggest. Commented Sep 3, 2014 at 5:28
  • It will work without GridFS, if your files are less 4Mb. But it's more flexible to use GridFS. It'll allow you to grow without changing your solution in the future. Commented Sep 3, 2014 at 5:39

1 Answer 1

2

Your problem here is not so much with storing and reading the data, but is actually all about content types. So ideally you want to store this with your data as well as return the correct header information when you send the response.

So part of this would be mime type detection. There are modules available, mmmagic is one of them

var Magic = require('mmmagic').Magic;

var magic = new Magic();

var data = fs.readFileSync(path);
var image = new mongodb.Binary(data);


//open connection/collection

magic.detect(data,function(err,result) {

    var record = {picname: id, content: image, mimeType: result };

    collection.save(record, {safe: true}, function(err,result){
        if(err)
            console.log(err.stack);
    });//save

});

Methods for writing the header vary, but with the base "http" for node you call as shown:

var record = {picname: id};
collection.findOne(record, function(err,result){
    if(err)
        console.log(err.stack);
    else {
        res.writeHead(200, {
            'Content-Type': result.mimeType,
            'Content-Length': result.content.length
        });
        res.write(result.content.buffer);
        res.end();
    }
});

So what effectively gets returned here is the binary data identified by it's correct mime type. So you can access this from an URL where you supply the means to lookup the document and view directly in a browser just as if it was a regular image file being served.

Sign up to request clarification or add additional context in comments.

2 Comments

application getting crash at content.length. So, added only result.mimetye. It's working fine for some files. not for all files.
For those looking for why it crashes, it should be result.content.buffer.length.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.