为什么findOne({id})在猫鼬6.012中无法正常工作



我正在使用mongoose根据其id查找一个用户,但它无法正常工作。我尝试了几种不同的方法,但只得到了错误的结果或错误。

这是我的密码。

const { id } = req.params;
const user = await User.findOne({ id });
console.log(id);
console.log(user);
return res.redirect("back");

我尝试了以下方法

1-await User.findOne({ id });返回第一个用户,无论id是什么。

target id: a8fc083f3f55494fa2cadf9
{
_id: new ObjectId("618fb03e37876d1f0bccb945"),
name: 'bohetefyhy',
email: 'refo@mailinator.com',
dataRealm: new ObjectId("618fb0119eefb1308fe65610"),
role: 'user',
createdAt: 2021-11-13T12:31:58.846Z,
updatedAt: 2021-11-15T08:03:34.422Z,
__v: 0
}

2-await User.findOne({ id: id });返回与上述(1(相同的结果。

3-await User.findOne({ _id: id });给出错误。

CastError: Cast to ObjectId failed for value "a8fc083f3f55494fa2cadf9" (type string) at path "_id" for model "User"
at model.Query.exec (C:UserskhanDocumentsProjects30FL014_Windshieldappnode_modulesmongooselibquery.js:4545:21)
at model.Query.Query.then (C:UserskhanDocumentsProjects30FL014_Windshieldappnode_modulesmongooselibquery.js:4644:15)
at processTicksAndRejections (internal/process/task_queues.js:97:5)

我还注意到,结果中缺少mongoose添加的id字段。并且对于_id值是新的ObjectId("618fb03e37876d1f0bccb945">(;618fb03e37876d1f0bccb945">

我正在使用

"猫鼬":"6.0.12〃;,

MongoDB 5.0.3 2008R2Plus SSL(64位(

好的,所以我发现了问题,我的对象Id中只有23个字符,从一开始就缺少一个。但仍然是为什么缺少mongoose添加的id字段,以及为什么id是新的ObjectId("618fb03e37876d1f0bccb945"(而不是简单的;618fb03e37876d1f0bccb945">当我记录时

我也遇到了同样的问题,这就是我获得所要查找的Id的数据的方法。

const ObjectId = require('mongodb').ObjectId;
const id = '61929f3efc232d63cd9dcb6b';
user.findOne({ _id: ObjectId(id) })
.then((result) => {
console.log(result);
})
.catch((err) => {
console.log(err);
});

这是我为用户信息提供的数据

用户信息数据

输出:

{
_id: new ObjectId("61929f3efc232d63cd9dcb6b"),
name: 'Ibrahem',
email: 'I-A-H@hotmail.com',
age: 24,
createdAt: 2021-11-15T17:56:14.089Z,
updatedAt: 2021-11-15T17:56:14.089Z,
__v: 0
}

我今天遇到了同样类型的问题,并通过社区指南解决了它。

我用这些简单的代码解决了它。也许你也可以试试。在这里,我用电子邮件尝试过,你可以用_id尝试。我发现它们都是有效的。

const router = require('express').Router();
const userModel = require('../models/usermodel');
router.post('/api/user/registration', async (req, res) => {
const emailX = req.body.email;
const emailExist = await userModel.findOne({'email': emailX }); // Finding the Email exist or not
console.log(emailX, "Email Exist: =>", emailExist);
})

Mongoose的findById方法将id参数强制转换为模型的_id字段的类型,这样它就可以正确地查询匹配的文档。

同时尝试检查

if (id.match(/^[0-9a-fA-F]{24}$/)) {
// Yes, it's a valid ObjectId, proceed with `findById` call.
}

var mongoose = require('mongoose');
mongoose.Types.ObjectId.isValid('your id here');

try:

await User.findOne({ _id: mongoose.Types.ObjectId(id) });

试试这个,我希望它能起作用:

const {id} = req.params
await User.findOne({_id: ObjectId(id)})

您可以通过添加以下代码开始调试该问题,并尝试检查mongoose查询是否传递了您传递的所有参数:

mongoose.set('debug', true);

我也面临着类似的问题,我能够通过使用id更新模式,如下所示:

_id:  mongoose.Types.ObjectId

我使用mongodb v6.0.0版本,这对我很有用。

const User = mongoose.model("User", userSchema); 
const userID="123123123123";
User.findOne({ _id: userID }, function (err, foundItem) { 
console.log("foundItem: "+foundItem);
}

userID类型:字符串

我希望它能在中工作

const { id } = req.params;
const user = await User.findById({ _id: id });

最新更新