Can you use find queries on GridFS using javascript API?

梦想与她 提交于 2019-12-11 18:24:09

问题


As I understand it, when you enter something into GridFS it gets entered into 2 different collections under the hood. One for the raw chunks of data and one for the meta data files.

Also from what I understand from MongoDB's documentation is that you can only retrieve a document from GridFS with an id or name.

var gs = new mongodb.GridStore(db, "test.png", "w", {
"content_type": "image/png",
"metadata":{
    "author": "Daniel"
},
"chunk_size": 1024*4

});

So what if I want to get a subset of documents from GridFS? For example what if I want all GridStores with:

metadata: {author: "Daniel"}

Why can't I use standard mongo queries { field: somevalue } and retrieve documents that way?

Does anybody know how this can be done? I'm using the javascript API on node.js.


回答1:


You can query the db.files collection just like any other collection:

db.collection('fs.files')
  .find({ 'metadata.author' : 'Daniel' })
  .toArray(function(err, files) {
    if (err) throw err;
    files.forEach(function(file) {
      var gs = new mongodb.GridStore(db, file._id, 'r');
      ...
    });
  });

Although instead of plain forEach you may want to use async.each or any of the other async.* methods.



来源:https://stackoverflow.com/questions/20379415/can-you-use-find-queries-on-gridfs-using-javascript-api

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