Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating a search endpoint in Mongo and NodeJS

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

>Solution :

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:

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading