Home > Back-end >  Creating a search endpoint in Mongo and NodeJS
Creating a search endpoint in Mongo and NodeJS

Time:01-08

I've been teaching myself basically a MERN CRUD project but haven't done anything on the front end as of yet. I have been able to get the API working properly on all the basic crud functionality. The thing I've been struggling with is constructing an endpoint that allows someone to search the MongoDB and return any matches.

I've been trying to pass a key that would be part of the HTTP GET request and use that with the Mongoose find function, but am not getting anywhere. I'll show what my working "findById" function looks like:

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

So I tried to model the search function based off of that:

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

The error I'm getting is "Parameter "filter" to find() must be an object" Any ideas appreciated, many thanks.

CodePudding user response:

The error "The 'filter' parameter to find() must be an object" indicates that you are passing an invalid value to the find method. In this case, you are passing req.params.key as a parameter, but the find method expects to receive a filter object as a parameter.

To fix this error, just pass a valid filter object to the find method. For example, if you want to search for all documents that have the field "name" with the value "John", the code would be:

  • Related