繁体   English   中英

在 Mongo 和 NodeJS 中创建搜索端点

[英]Creating a search endpoint in Mongo and NodeJS

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

我一直在尝试传递一个密钥,该密钥将成为 HTTP GET 请求的一部分,并将其与 Mongoose 一起使用,查找 function,但我没有得到任何结果。 我将展示我的工作“findById”function 的样子:

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,
      });
    });
};

所以我尝试 model 搜索 function 基于:

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);
  })}

我得到的错误是“find() 的参数“过滤器”必须是一个对象”任何想法表示赞赏,非常感谢。

错误“find() 的‘filter’参数必须是一个对象”表示您将无效值传递给 find 方法。 在这种情况下,您将 req.params.key 作为参数传递,但 find 方法期望接收过滤器 object 作为参数。

要修复此错误,只需将有效过滤器 object 传递给查找方法即可。 例如,如果要搜索字段“name”的值为“John”的所有文档,代码为:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM