字段"/>
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 查询文本字段
发布评论