Mongoose NodeJs 查询文本字段

编程入门 行业动态 更新时间:2024-10-04 21:26:46

Mongoose NodeJs 查询文本<a href=https://www.elefans.com/category/jswz/34/1771443.html style=字段"/>

Mongoose NodeJs 查询文本字段

我在使用

Nodejs
和 Mongoose 制作 CRUD API 端点时遇到问题。

export const getRecipes: RequestHandler = async (req, res, next) => {
    try {
        const { _page = 1, _limit = 10, _order = 1, title_like = '' } = req.query;
        const _sort =
            (req.query._sort && _order)
                ? Object.fromEntries([[req.query._sort, Number(_order)]])
                : { "createAt": 1 };

        console.log(_sort);
        console.log(title_like);
        const recipes = await RecipeModel
            .find({ title: { $regex: title_like } })
            .collation({ locale: "vi", strength: 1 })
            .populate('ingredients', 'title')
            .sort(_sort)
            .limit(Number(_limit) * 1)
            .skip((Number(_page) - 1) * Number(_limit))
            .exec();

        res.status(200).json(recipes);
    } catch (error) {
        next(error);
    }
}

当我从 ReactJS 客户端调用 API 时,这不起作用。但是如果我硬编码:

find({ title: { $regex: "Bò" } })
我得到了我期望的结果。有办法解决这个问题吗?

我也试过

find({ $text: { $search: title_like } })
但它显示错误:键入'string |已解析的问题 |字符串[] | parsedqs[]' 不可分配给类型 'string'。我确实索引了标题字段。

回答如下:

更多推荐

Mongoose NodeJs 查询文本字段

本文发布于:2024-05-30 20:33:51,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1770894.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字段   文本   Mongoose   NodeJs

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!