skip to Main Content

Model.findOne() is returning null even if the valid collection is present in the respective Model


app.post("/fleetManagement", (req, res) => {

  const requestedDriverID = req.body.driverId;
  console.log(requestedDriverID);

  Driver.findOne({
      _id: requestedDriverID
  }, function(err, requestedDriverResult) {
      console.log(requestedDriverResult);
      res.render("fleetManagement", {
          reqDriver: requestedDriverResult
      });
  });
})

Output
Collection in Driver Model

Check out the Output and Collection of Driver Model

2

Answers


  1. Try convert requestedDriverID to ObjectId(requestedDriverID)

    Login or Signup to reply.
  2. You need to convert the _id input to ObjectId.
    Here’s the updated code for your reference:

    
    app.post("/fleetManagement",(req, res)=>{
    
    const requestedDriverID = req.body.driverId;
    console.log( requestedDriverID);
    
    Driver.findOne({_id: ObjectId(requestedDriverID)  }, function(err, requestedDriverResult){
    console.log(requestedDriverResult);
      res.render("fleetManagement", {
        reqDriver:requestedDriverResult
        });
      });
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search