Why gridfs get doesn't work with file identifier (ObjectId) only by file name

I am using nodejs mongodb mongoose and gridfs. when I try to get the file from it, filname everthing works fine, if I want to get it by the id that I get Error: the file you want to read does not exist. I have the following console.log code ("res.pic_id:" + res.pic_id), I get the correct ObjectId. Here is 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))); } } }) 

Thanks!

+4
source share
2 answers

I had a similar problem. The problem turned out to be that I used the string representation of 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'); 
+5
source

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

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

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

+4
source

All Articles