在本地运行,但是在线访问一个Atlas MongoDb数据库,我具有如下构建器数据:
[
{
"_id": "5ec63e97516541c07c2b26d3",
"name": "Bob"
},
{
"_id": "5ec64261b9be7b08cb8d7ba9",
"name": "builder post test"
}
]
真的很简单,但是问题是当我定义CRUD动作时:我希望能够从上面的ID中获得特定的生成器,例如Bob。我的代码在server.js文件中,如下所示:
server.get("/:id", (request, response) => {
const itemId = request.params.id;
dbCollection.findOne({id: itemId }, (error, result) => {
if (error) throw error;
response.json(result);
});
});
[每当我测试端点:http://localhost:4000/5ec63e97516541c07c2b26d3
我返回null。我已经登录了控制台,并确保id正确输入。我什至更改了id-> _id以匹配模式,但仍然为null。
当我将上面id的findOne初始参数更改为name时,我可以访问端点http://localhost:4000/Bob:>
server.get("/:id", (request, response) => { const itemId = request.params.id; dbCollection.findOne({name: itemId }, (error, result) => { if (error) throw error; response.json(result); }); });
我对为什么名称有效但id无效的原因感到困惑,我觉得我错过了一些基本的知识,任何帮助或建议都值得赞赏!
[在本地运行,但是在线访问一个atlas MongoDb数据库,我具有以下构建器数据:[{“ _id”:“ 5ec63e97516541c07c2b26d3”,“ name”:“ Bob”},{“ _id”:“ ...
如果使用的是mongodb本机驱动器,则需要先转换为ObjectID。