Problem with MongoDB GridFS Saving Files with Node.JS

纵饮孤独 提交于 2019-12-17 19:29:40

问题


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    });

回答1:


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.

https://github.com/christkv/node-mongodb-native/tree/master/test/gridstore



来源:https://stackoverflow.com/questions/6936396/problem-with-mongodb-gridfs-saving-files-with-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!