为什么gridfs get不能仅按文件名处理文件ID(ObjectId) [英] Why gridfs get isn't working on file id (ObjectId) only by filename

查看:110
本文介绍了为什么gridfs get不能仅按文件名处理文件ID(ObjectId)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

        }
    }
})

谢谢!

推荐答案

我遇到了类似的问题.结果是我使用的是ObjectID的字符串表示形式,而不是实际的ObjectID.代替这个:

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

我需要这样做:

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

这篇关于为什么gridfs get不能仅按文件名处理文件ID(ObjectId)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆