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!
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.
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.
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.
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');
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With