当文档存在时从 findOne() 返回 null

Returning null from findOne() when document exists

在本地

运行,在网上访问一个图集MongoDb DB,我有builder的数据如下:

 [
   {
   "_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

我得到空返回。我已经登录控制台并确保输入的 id 是正确的。我什至更改了 id --> _id 以匹配架构但仍然为空。

当我将上面的 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);
          });
       });

我很困惑为什么 name 有效但 id 无效,我觉得我错过了一些基本的东西,感谢任何帮助或建议!

如果您使用的是 mongodb 本机驱动器,则需要先转换为 ObjectID。

const ObjectId = require('mongodb').ObjectID;

exports.findUserById = (req, res, next) => {
    db.get().collection('user').findOne({ _id: new ObjectId(req.params.id) }).then((result) => {
        if (result === null) {
            res.status(404).json({ errors: [{location: "users", msg: "Not found", param: req.params.id}]})
        }
        req.usuario = result;
        next()
    }).catch((err) => {
        res.status(500).json({ errors: [{location: "users", msg: err, param: req.params}]})
    })
}