Nick Hodges
Nick Hodges

Reputation: 17138

How do I filter records with a REST API using Express and Mongoose?

I am building a classic Todo server using Express and Mongoose. Here is my model:

import mongoose = require('mongoose');
const autoIncrement = require('mongoose-sequence')(mongoose);

const TodoSchema: mongoose.Schema = new mongoose.Schema({
  todoid: {
    type: Number
  },
  title: {
    type: String,
    required: 'Enter a title'
  },
  note: {
    type: String
  },
  complete: {
    type: Boolean,
    default: false
  },
  editMode: {
    type: Boolean,
    default: false
  }
});

TodoSchema.plugin(autoIncrement, {
  inc_field: 'todoid',
  start_seq: 422
});

export { TodoSchema };

I want to process the following REST API query:

http://localhost:3000/todos?complete=true

I can FindOne and that kind of basic thing, but I can't seem to figure out the code to filter the results of a GET call to return only the completed todos.

What is the proper way to do that?

Upvotes: 0

Views: 743

Answers (1)

Suresh Prajapati
Suresh Prajapati

Reputation: 4477

You can use find function to query based on completed:

async function getTodohandler(req, res){
  var result = await TodoSchema.find({completed: req.query.completed == "true"})
  return res.send(result)
}

Upvotes: 1

Related Questions