How to create an endpoint with optional parameters? (Node, Express, MongoDB)

Viewed 335

I have created a MongoDB with two main entities CATS and BREEDS (one-to-many) but I have never worked with optional parameters.

I want to handle the following requests.

  • A 'GET' request to fetch all the cats (with an optional param that will determine if the description should be returned as well, and another optional param to filter by breed)

  • A 'GET request to fetch a specific cat (with an optional param that will determine if the payload will be returned as well) either by name or by id

I include my DB schemas in case they are needed.

const CatSchema = new Schema({
    name: { type: String, required: true, trim: true },
    description: { type: String, required: true, trim: true },
    breed: {
        type: Schema.Types.ObjectId,
        ref: "Breed"
    }
});

const BreedSchema = new Schema({
    name: { type: String, required: true, trim: true }
});
1 Answers

Use a question mark to make your param optional. /cats/:description?

You can also use multiple optional parameters. /cats/:description?/:breed?

Edit, be sure to check the params with:

if(description) {
    //show cats with description
} 

Something like that.

Related