Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why gridfs get isn't working on file id (ObjectId) only by filename

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!

like image 472
Liatz Avatar asked Dec 08 '12 13:12

Liatz


People also ask

How do I get the Objectid after I save an object in mongoose?

To get the object ID after an object is saved in Mongoose, we can get the value from the callback that's run after we call save . const { Schema } = require('mongoose') mongoose. connect('mongodb://localhost/lol', (err) => { if (err) { console. log(err) } }); const ChatSchema = new Schema({ name: String }); mongoose.

What is the default size of a GridFS chunk?

By default, GridFS uses a default chunk size of 255 kB; that is, GridFS divides a file into chunks of 255 kB with the exception of the last chunk. The last chunk is only as large as necessary.

What is bucket in GridFS?

A GridFS “bucket” is the combination of an “fs. files” and “fs. chunks” collection which together represent a bucket where GridFS files can be stored.


2 Answers

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');
like image 69
Brad Avatar answered Sep 22 '22 15:09

Brad


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

like image 34
christkv Avatar answered Sep 26 '22 15:09

christkv