You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 02:55:24