mongoose 模型.findOne()返回空值

u2nhd7ah  于 2022-11-13  发布在  Go
关注(0)|答案(2)|浏览(239)

即使相应的Model中存在有效集合,Model.findOne()也返回null

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

OutputCollection in Driver Model显示器
查看驱动程序模型的输出和收集

iibxawm4

iibxawm41#

尝试将请求的驱动程序ID转换为对象ID(请求的驱动程序ID)

7kqas0il

7kqas0il2#

您需要将_id输入转换为ObjectId。以下是更新后的代码供您参考:

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

相关问题