node.js 错误 ReferenceError: ObjectID 未定义

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22143090/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:57:06  来源:igfitidea点击:

error ReferenceError: ObjectID is not defined

node.jsangularjsmongodb

提问by Anup

I want to upload image with GridJS. I am using https://www.npmjs.org/package/gridfs-streamfor this. It gives me errorReferenceError: ObjectID is not defined.

我想用 GridJS 上传图片。我为此使用https://www.npmjs.org/package/gridfs-stream。它给了我errorReferenceError: ObjectID is not defined

I am beginner to this, so have no idea whats going.

我是初学者,所以不知道发生了什么。

How to solve this error?

如何解决这个错误?

var Grid = require('gridfs-stream');
    var conn = mongoose.createConnection('localhost', 'Test', 27017);
    var gfs = Grid(conn.db, mongoose);

    var fileId = new ObjectID(uniqId);
    var fileType = req.header('X-File-Type');
    var fileName = req.header('X-File-Name');
    var uniqId = req.param('uniqId', '112211112111');

    console.log('upload start');
    // streaming to gridfs
    var writestream = gfs.createWriteStream(fileId, [{ "content_type": fileType, "metadata": { "fileName": fileName, "uploaded_at": (new Date()).toString() } }]);
    fs.createReadStream('/some/path').pipe(writestream);

    // streaming from gridfs
    var readstream = gfs.createReadStream(fileId, [{ "content_type": fileType, "metadata": { "fileName": fileName, "uploaded_at": (new Date()).toString() } }]);

    //error handling, e.g. file does not exist
    readstream.on('error', function (err) {
        console.log('An error occurred!', err);
        throw err;
    });

    readstream.pipe(response);
    console.log('upload done');

回答by Illegal Argument

Not directly a solution but a small typo wasted 10 minutes of my time:

不是直接的解决方案,而是一个小错误浪费了我 10 分钟的时间:

var ObjectId = require('mongodb').ObjectID;

I declared a variable ObjectId with small dbut when using the variable, I tried ObjectIDwith capital D.

我用小d声明了一个变量 ObjectId ,但是在使用该变量时,我尝试用大写D 表示ObjectID

回答by Paul Mougel

ObjectIDis not a global variable, it is defined by mongoose (see the documentation):

ObjectID不是全局变量,它是由 mongoose 定义的(参见文档):

var fileId = mongoose.Types.ObjectId();