如果没有“new”,则无法调用类构造函数ObjectId

问题描述 投票:0回答:1

我正在尝试从本地 mongodb 数据库中使用express中的

get
方法,对于请求
/Movies/:id
,它应该提取电影的详细信息。但它却在下面向我抛出一个错误

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)

Mongdb版本:5.0.18

代码片段:

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")
    }
})
node.js mongodb express
1个回答
0
投票
app.get('/Movies/:id',(req,res)=>{

if(ObjectId.isValid(req.params.id)){
    db.collection('Movies')
        .findOne({_id: ObjectId.createFromHexString(req.params.id)})
        .then(result=>{
            res.status(200).json(result)
        })
        .catch((err)=>{
            res.status(404).send(err)
        })
}
else{
    res.status(400).send("Invalid ID")
}

尝试使用 ObjectId.createFromHexString() 而不是 ObjectId() 来转换您的 id

© www.soinside.com 2019 - 2024. All rights reserved.