5

I'm using nodejs mongodb mongoose and gridfs. when I try to get a file by it's filname everthing is working great by if i want to get it by id i get Error: The file you wish to read does not exist. I the following code the console.log("res.pic_id : " + res.pic_id) i get the correct ObjectId. Here's the code :

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

        }
    }
})

Thank you!

Liatz
  • 4,997
  • 7
  • 28
  • 33

3 Answers3

7

I had a similar problem. The issue turned out to be that I was using the string representation of an ObjectID instead of the real ObjectID. Instead of this:

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

I needed to do this:

var gridStore = new GridStore(db, new ObjectID('51299e0881b8e10011000001'), 'r');
Brad
  • 159,648
  • 54
  • 349
  • 530
4

You have to either store it as a file name or object.id as primary key. The best way is to store it with ObjectID as an identifier and then add the filename to the metadata and query using that.

Look at the third example from the documentation (this is in the case of the native driver with lies under mongoose)

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

christkv
  • 4,370
  • 23
  • 21
  • 2
    this answer is 100% correct and needs to be marked as so for the poor google query traffic!! – lol Mar 21 '15 at 14:24
0

You can create a Mongodb Object using mongoose:

const mongoose = require('mongoose');

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

Now you can get files and do whatever other stuff using gridfs and fileID, ex:

let gfs = Grid(mongoose.createConnection(mongoURI), mongoose.mongo);
app.get('URI', function(req, res){  //...

    gfs.files.findOne({_id: fileId}, //callback...

    )
})

That worked just fine for me.

Sverissimo
  • 276
  • 4
  • 8