Problem with MongoDB GridFS Saving Files with Node.JS

Problem

I have a function saving a file to gridfs. It somehow stopped working sporadically after a refactor and I’ve spent over 2 hours staring blankly at it. I swear it’s roughly the same as it was. I seem to remember it not working at first before I added close, then it started working, but it could be the insomnia. Essentially the issue is the db.fs.files collection doesn’t have any records, but chunks are getting added to db.fs.chunks.

data is a buffer loaded from disk via fs.readFile()

31    var gs = new mongodb.GridStore(this.db, filename, "w", {
32 "chunk_size": 1024*4,
33 metadata: {
34 hashpath:gridfs_name,
35 hash:hash,
36 name: name
39 }
40 });
41 gs.open(function(err,store) {
42 gs.write(data,function(err,chunk) {
43 //cb(err,hash,chunk);
44 //self.close();
45 });
46 });

Problem courtesy of: Justin Thomas

Solution

There are a couple of solutions. You can use writeBuffer, writeFile or the new simple grid class. Under is your example adjusted for the fact of using a buffer instance.

// You can use an object id as well as filename now
var gs = new mongodb.GridStore(this.db, filename, "w", {
"chunk_size": 1024*4,
metadata: {
hashpath:gridfs_name,
hash:hash,
name: name
}
});

gs.open(function(err,store) {
// Write data and automatically close on finished write
gs.writeBuffer(data, true, function(err,chunk) {
// Each file has an md5 in the file structure
cb(err,hash,chunk);
});
});

In general the best place to start are the tests that cover a wide usage profile for the gridfs classes. Look at.

Solution courtesy of: christkv

View additional discussion.