MongoError: filter参数必须是一个对象。

4

我正在创建一个REST API,其中我有一个用于Post/Movies的端点:请求体应仅包含电影标题,并且应验证其是否存在。根据传递的标题,应从themoviedb中获取其他电影详细信息,并保存到应用程序数据库中。

app.post('/movies', (req, res) => {
        request('https://api.themoviedb.org/3/discover/movie?callback=JSONP_CALLBACK&sort_by=popularity.desc&api_key=2931998c3a80d7806199320f76d65298', function (error, response, body) {
            console.log('error:', error); // Print the error if one occurred and handle it
            console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received

          });
        db.collection('movies').findOneAndUpdate(req.body.title,{
            title: 'Avengers',
        },(err, result) => {
            if (err) {
                res.send({
                    'error': 'An error has occured'
                });
            } else {
                res.send(result.ops[0]);
            }
        });
});

当我运行这个应用程序时,我遇到了这个错误,我在这里做错了什么?我是nodejs的新手,正在学习所有这些东西。

1
req.body.title并不是一个"对象"。实际上,它看起来更像是一个打字错误,下一个可能是{title:'复仇者联盟'}这样的内容才是你想表达的。或者可能是{title:req.body.title}。总之,看起来你忘记删除测试代码并在错误的地方添加了变量。 - Neil Lunn
2个回答

4

在过滤器对象中使用$eq运算符$eq

{ <field>: { $eq: <value> } }

因此,最终的代码段将变成以下样式:
app.post('/movies', (req, res) => {

    /* code ... */

    let { title } = req.body

    db.collection('movies').findOneAndUpdate({ title: { $eq: title } }, { title: 'Avengers' }, (err, result) => {
        if (err) {
            res.send({ 'error': 'An error has occured' });
        } else {
            res.send(result.ops[0]);
        }
    });

});

当我运行localhost:8000/movies时,在控制台中出现错误TypeError: Cannot read property '0' of undefined,而在Postman中无法获得任何响应。 - Hot Zellah
尝试使用 console.log(result) 查看JSON的结构。 - Adam Azad
这是我得到的内容:我们在8000端口上运行 { lastErrorObject: { updatedExisting: false, n: 0 }, value: null, ok: 1 } 错误:null 状态码:200 - Hot Zellah

0

请尝试以下方法:

db.collection('movies').findOneAndUpdate({title:req.body.title},{
          $set:{
           'Avengers'
          }})

意外的 Token,}? - Hot Zellah
可能我没有正确地关闭它,请检查你的代码中的'}'。 - Sajeetharan
设置方法似乎有问题,请再次检查是否正确,右括号都没问题。 - Hot Zellah
1
https://github.com/freespiritdev/Media/blob/d7d21e4145c28f6437ccfd6b2cb4abda04ea31e4/server/server.js - Sajeetharan
答案有帮助吗? - Sajeetharan
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接