Search code examples
javascriptnode.jsmongodbnodemonmongodb-atlas

Returning null from findOne() when document exists


Running locally, but accessing an atlas MongoDb DB online, I have builder's data as follows:

 [
   {
   "_id": "5ec63e97516541c07c2b26d3",
   "name": "Bob"
   },

  {
  "_id": "5ec64261b9be7b08cb8d7ba9",
  "name": "builder post test"
  }
]

Really simple, but the problem is when I'm defining my CRUD actions: I want to be able to get a specific builder, say Bob, from his id above. My code is in my server.js file is as follows:

server.get("/:id", (request, response) => {
      const itemId = request.params.id;

      dbCollection.findOne({id: itemId }, (error, result) => {
         if (error) throw error;
         response.json(result);
      });
   });

Whenever I test the endpoint: http://localhost:4000/5ec63e97516541c07c2b26d3

I get null returned. I've console logged and made sure id is correct coming in. I've even changed id --> _id to match the schema but still null.

I can access the endpoint http://localhost:4000/Bob when I changed the findOne initial parameter of id above to name:

server.get("/:id", (request, response) => {
          const itemId = request.params.id;

          dbCollection.findOne({name: itemId }, (error, result) => {
             if (error) throw error;
             response.json(result);
          });
       });

I'm stumped as to why name works but id doesn't, I feel like I've missed something basic, any help or advice appreciated!


Solution

  • If you are using mongodb native drive you need to cast to ObjectID first.

    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}]})
        })
    }