[英]MongoDB findOne funtion returns null when comparing with id
I am using the following code to get the details of a user when I pass their id as a parameter:当我将用户的 id 作为参数传递时,我正在使用以下代码获取用户的详细信息:
server.get("/users/:id", (req, res) => {
const itemId = req.params.id;
dbCollection.findOne({ _id: itemId }, (error, result) => {
if (error) throw error;
// return item
res.json(result);
});
});
However, this doesn't seem to work, as whenever I run the code, I get returned with a null value.但是,这似乎不起作用,因为每当我运行代码时,都会返回 null 值。 My question is not the same as many previously asked questions because I have
ObjectId('randomId')
as my id, and not a string.我的问题与许多以前提出的问题不同,因为我的 ID 是
ObjectId('randomId')
,而不是字符串。 How can I fix my code?如何修复我的代码?
req.params.id
comes as a string while your _id
is an ObjectId so this won't work since MongoDB requires type equality first, you need to cast the value: req.params.id
是一个字符串,而你的_id
是一个 ObjectId 所以这不起作用,因为 MongoDB 首先需要类型相等,你需要转换值:
const itemId = mongoose.Types.ObjectId(req.params.id);
MongoDB wouldn't consider the "itemId" as a MongoDB id, therefore you need to transform it as shown below: MongoDB 不会将“itemId”视为 MongoDB id,因此您需要将其转换为如下所示:
new mongodb.ObjectId(itemId)
This implies that:这意味着:
const mongodb = require('mongodb')
As others already said, MongoDB expects _id
to be an ObjectID.正如其他人已经说过的,MongoDB 期望
_id
是一个 ObjectID。 But if you are searching for ONE item, instead of using findOne
use findById
, which accepts id as a string.但是,如果您正在搜索 ONE 项目,而不是使用
findOne
使用findById
,它接受 id 作为字符串。
const { Model } = require('./models'); // Model is your Mongoose Schema
server.get("/users/:id", async (req, res) => {
const { id } = req.params;
// This is the same as Model.findOne({ _id: new ObjectId(id) });
const item = await Model.findById(id);
return res.json(item);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.