angularjs 错误引用错误:未定义ObjectID

jtw3ybtb  于 2022-10-31  发布在  Angular
关注(0)|答案(4)|浏览(276)

我想用GridJS上传图片。我使用https://www.npmjs.org/package/gridfs-stream。它给我errorReferenceError: 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');
2skhul33

2skhul331#

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

var fileId = mongoose.Types.ObjectId();
lb3vh1jj

lb3vh1jj2#

试试这个。它可以在你的代码中正常工作。

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

hs1rzwqc3#

您可以使用下面的代码来获取ObjectId

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

如果您想使用它

db.collection.deleteOne({_id:new  
      ObjectID(req.params._id)}).then(data=>{

        res.send({status:"Success",data:data});
    })
lymgl2op

lymgl2op4#

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

ObjectID(大写“D”)已过时。请改用ObjectID(小写“d”)。(源代码:@包类型/桶

相关问题