MongoDB GridFS使用Node.JS保存文件时出现问题 [英] Problem with MongoDB GridFS Saving Files with Node.JS

查看:79
本文介绍了MongoDB GridFS使用Node.JS保存文件时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个将文件保存到gridfs的功能.重构后它以某种方式停止工作,我花了两个多小时呆呆地盯着它看.我发誓与以前大致相同.我似乎记得起先添加它之前它不起作用,然后才开始起作用,但这可能是失眠.从本质上讲,问题在于db.fs.files集合没有任何记录,但是将块添加到db.fs.chunks中.

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.

数据是通过fs.readFile()从磁盘加载的缓冲区

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

推荐答案

有两种解决方案.您可以使用writeBuffer,writeFile或新的简单网格类.在下面的示例中,针对使用缓冲区实例的事实进行了调整.

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

通常,最好的起点是覆盖gridfs类的广泛使用情况的测试.看.

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

这篇关于MongoDB GridFS使用Node.JS保存文件时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆