Express调用MongoDB报错:Class constructor ObjectId cannot be invoked without 'new'
解决Express中MongoDB ObjectId调用报错问题
问题描述
在Express中通过GET请求/Movies/:id从本地MongoDB(版本5.0.18)获取对应电影详情时,触发如下错误:
TypeError: Class constructor ObjectId cannot be invoked without 'new' at /home/srithan/Desktop/Right_doc/Tutorial/mongodb/Mongo/app.js:59:24 at Layer.handle [as handle_request] (/home/srithan/Desktop/Right_doc/Tutorial/mongodb/Mongo/node_modules/express/lib/router/layer.js:95:5) at next (/home/srithan/Desktop/Right_doc/Tutorial/mongodb/Mongo/node_modules/express/lib/router/route.js:144:13) at Route.dispatch (/home/srithan/Desktop/Right_doc/Tutorial/mongodb/Mongo/node_modules/express/lib/router/route.js:114:3) at Layer.handle [as handle_request] (/home/srithan/Desktop/Right_doc/Tutorial/mongodb/Mongo/node_modules/express/lib/router/layer.js:95:5) at /home/srithan/Desktop/Right_doc/Tutorial/mongodb/Mongo/node_modules/express/lib/router/index.js:284:15 at param (/home/srithan/Desktop/Right_doc/Tutorial/mongodb/Mongo/node_modules/express/lib/router/index.js:365:14) at param (/home/srithan/Desktop/Right_doc/Tutorial/mongodb/Mongo/node_modules/express/lib/router/index.js:376:14) at Function.process_params (/home/srithan/Desktop/Right_doc/Tutorial/mongodb/Mongo/node_modules/express/lib/router/index.js:421:3) at next (/home/srithan/Desktop/Right_doc/Tutorial/mongodb/Mongo/node_modules/express/lib/router/index.js:280:10)
涉及的代码片段:
app.get('/Movies/:id',(req,res)=>{ if(ObjectId.isValid(req.params.id)){ db.collection('Movies') .findOne({_id: ObjectId(req.params.id)}) .then(result=>{ res.status(200).json(result) }) .catch((err)=>{ res.status(404).send(err) }) } else{ res.status(400).send("Invalid ID") } })
错误原因
MongoDB驱动中的ObjectId是类类型,必须使用new关键字实例化才能生成有效的ObjectId对象,直接调用ObjectId(req.params.id)不符合类的调用规范,因此报错。
解决方案
1. 添加new关键字实例化ObjectId
修改findOne查询条件中的ObjectId调用,加上new:
app.get('/Movies/:id',(req,res)=>{ if(ObjectId.isValid(req.params.id)){ db.collection('Movies') .findOne({_id: new ObjectId(req.params.id)}) // 新增new关键字 .then(result=>{ res.status(200).json(result) }) .catch((err)=>{ res.status(404).send(err) }) } else{ res.status(400).send("Invalid ID") } })
2. 确保正确导入ObjectId
同时要确认你已经从mongodb包中正确导入了ObjectId:
const { ObjectId } = require('mongodb');
内容的提问来源于stack exchange,提问作者Ramavath Sai Srithan
相关产品推荐
相关产品推荐

