error ReferenceError:未定义ObjectID

时间:2014-03-03 09:35:42

标签: node.js angularjs mongodb

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

我是初学者,所以不知道最新情况。

如何解决此错误?

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

3 个答案:

答案 0 :(得分:13)

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

var fileId = mongoose.Types.ObjectId();

答案 1 :(得分:6)

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

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

我声明了一个带有 d 的变量ObjectId,但在使用该变量时,我尝试使用 D ObjectID

答案 2 :(得分:-1)

Refer Mongoose Promise Docs

const mongoose = require('mongoose');

_id: mongoose.Types.ObjectId("5bd45c4b9524a22dd05a78f2")