Mongoose:通过 slug $ 或 id 查找
我正在尝试路由 /:slug,用户可以输入 _id 或 slugify 生成的 slug。
我正在路由控制器上尝试这个:
const query = await Tour.find({
$or: [{ _id: req.params.slug }, { slug: req.params.slug }]
});
但它不起作用,我只有在这样做时才能使其工作:
if (req.params.slug.includes('-')) {
query = await Tour.find({ slug: req.params.slug });
} else {
query = await Tour.findById(req.params.slug);
}
问题是:我使用 $or 运算符做错了什么?提前致谢
i'm trying to route /:slug and the user can type the _id or a slug generated by slugify.
i'm trying this on the route controller:
const query = await Tour.find({
$or: [{ _id: req.params.slug }, { slug: req.params.slug }]
});
but it doesn't work, i only manage to make it work when i do this:
if (req.params.slug.includes('-')) {
query = await Tour.find({ slug: req.params.slug });
} else {
query = await Tour.findById(req.params.slug);
}
the question is: what am i doing wrong using $or operator? thanks in advance
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我一直在为同样的实施而苦苦挣扎。
为了让它工作:
这里的技巧是像
{ _id: Types.ObjectId(slug) }
一样查询 id,但问题是如果slug
实际上是一个 slug 并且不是 ObjectId,Types.ObjectId(slug)
会破坏代码。因此,使用isValidObjectId
进行检查非常重要。我从猫鼬警告和这里的许多答案中得到了这个提示:
I have been struggling with the same implementation.
To make it work:
The trick here was to query the id like
{ _id: Types.ObjectId(slug) }
, but the thing is ifslug
is actually a slug and not an ObjectId,Types.ObjectId(slug)
will break the code. So it's important to make a check usingisValidObjectId
.I got this tip from a Mongoose warning and through many answers here: