用Mongo和NodeJS创建一个搜索端点



我一直在自学一个MERN CRUD项目,但到目前为止还没有在前端做任何事情。我已经能够让API在所有基本的crud功能上正常工作。我一直在努力构建一个端点,允许某人搜索MongoDB并返回任何匹配。

我一直试图传递一个密钥,这将是HTTP GET请求的一部分,并使用猫鼬查找功能,但我没有得到任何地方。我将展示我的工作&;findbyid &;函数看起来像:

exports.findOne = (req, res) => {
App.findById(req.params.noteId)
.then((data) => {
if (!data) {
return res.status(404).send({
note: "Note not found with id " + req.params.noteId,
});
}
res.send(data);
})
.catch((err) => {
if (err.kind === "ObjectId") {
return res.status(404).send({
note: "Note not found with id " + req.params.noteId,
});
}
return res.status(500).send({
note: "Error retrieving note with id " + req.params.noteId,
});
});
};

所以我尝试在此基础上建立搜索函数模型:

exports.search = async (req, res) => {
App.find(req.params.key)
.then((data) => {
if (!data) {
return res.status(404).send({
note: "Note not found with search query: " + req.params.key,
});
}
res.send(data);
})}

得到的错误是"Parameter "filter"To find()必须是对象"如有任何意见,不胜感激。

错误"查找()的'filter'参数必须是一个对象"指示您正在向查找方法传递无效值。在本例中,您将req.params.key作为参数传递,但是find方法希望接收一个过滤器对象作为参数。

要修复此错误,只需向find方法传递一个有效的筛选器对象。例如,如果您想要搜索包含"name"字段的所有文档;对于值"John",代码将是:

相关内容

最新更新