我需要通过他的mongodb收藏找到一个用户。_id
,
需要用用户ID中的前5个字符进行搜索
例子与 5e9cca
我可以找到收藏的ID 5e9cca24beabb96a4caedc35
var id = req.body.id
User.findById({ _id : { $regex: '^id', $options: 'i' } },
(err, user) => {
if (err) {
console.log(err);
res.status(400)
}
用这个代码我得到了这个错误。
MongooseError [CastError]: Cast to ObjectId failed for value "{ _id: { '$regex': '^id', '$options': 'i' } }" at path "_id" for model "User"
PS : 使用孔ID进行搜索是可行的。
Mongoose的 .findById() 将会接收一个字符串& 在内部它将会把字符串转换为 ObjectId()
. 所以... .findById()
是MongoDB原生函数的一种封装器。.findOne()
而它能带走的只是一个字符串。此外,你不能对以下内容进行regex搜索 _id
字段,因为它不属于 string
. 如果你需要这样做,请尝试以下。
在MongoDB版本>4.0 :
db.collection.aggregate([
/** Create a field of type 'string' from `_id`*/
{ $addFields: { convertedId: { $toString: "$_id" } } },
/** Regex search against it */
{
$match: {
convertedId: {
$regex: "^1a934e",
$options: "i"
}
}
},
/** Remove additionally added field */
{ $project: { convertedId: 0 } }
])
测试 : mongoplayground