【问题标题】:Why gridfs get isn't working on file id (ObjectId) only by filename为什么gridfs get不能仅通过文件名处理文件ID(ObjectId)
【发布时间】:2012-11-26 12:14:35
【问题描述】:

我正在使用 nodejs mongodb mongoose 和 gridfs。 当我尝试通过文件名获取文件时,如果我想通过 id 获取文件,一切都很好 错误:您要读取的文件不存在。 我使用以下代码 console.log("res.pic_id : " + res.pic_id) 我得到了正确的 ObjectId。 这是代码:

var GridFS = require('GridFS').GridFS;
var myFS = new GridFS('db');
var fs = require('fs')
var Profile = db.model('Profile');
Profile.findOne({'_id' : clientID},['_id', 'username','pic_id','pic_filename'],function(err, res){
    if (err) { 
        console.log("ERROR serching user info:  " + err);
        callback(JSON.stringify(JSONRes(false, err)));
    }
    else {
         if (res) {
        console.log("res.pic_id : " + res.pic_id);
        myFS.get(res.pic_id,function(err,data){
            if (err)
                console.log("ERROR "+err)
            else {
                callback(data);
            }})
        };
        }
        else {
        callback(JSON.stringify(JSONRes(false, err)));

        }
    }
})

谢谢!

【问题讨论】:

    标签: node.js mongodb gridfs


    【解决方案1】:

    我遇到了类似的问题。问题原来是我使用的是 ObjectID 的字符串表示,而不是真正的 ObjectID。而不是这个:

    var gridStore = new GridStore(db, '51299e0881b8e10011000001', 'r');
    

    我需要这样做:

    var gridStore = new GridStore(db, new ObjectID('51299e0881b8e10011000001'), 'r');
    

    【讨论】:

      【解决方案2】:

      您必须将其存储为文件名或 object.id 作为主键。最好的方法是使用 ObjectID 作为标识符存储它,然后将文件名添加到元数据并使用它进行查询。

      查看文档中的第三个示例(这是在本机驱动程序的情况下,位于 mongoose 下)

      http://mongodb.github.com/node-mongodb-native/api-generated/gridstore.html#open

      【讨论】:

      • 这个答案是 100% 正确的,对于糟糕的谷歌查询流量需要标记为如此!
      【解决方案3】:

      你可以使用 mongoose 创建一个 Mongodb 对象:

      const mongoose = require('mongoose');
      
      const fileId = new mongoose.mongo.ObjectId(req.params.id);`
      

      现在您可以使用 gridfs 和 fileID 获取文件并执行任何其他操作,例如:

      let gfs = Grid(mongoose.createConnection(mongoURI), mongoose.mongo);
      app.get('URI', function(req, res){  //...
      
          gfs.files.findOne({_id: fileId}, //callback...
      
          )
      })
      

      这对我来说效果很好。

      【讨论】:

        猜你喜欢
        • 2012-08-20
        • 2010-12-12
        • 2020-11-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多