manutdfan
manutdfan

Reputation: 295

MEAN Stack: Expressjs Routes with query parameters

I have two separate schemas- 1. User 2. Plans. I am trying to find all the plans that belong to a user, but doing a get request using query parameters is not working.Please help.

Here is my query

http://localhost:8080/api/plans/search?userId=56bd16761e6bb0e5b2b43c9b

I get all the plans via this route so that is working.

http://localhost:8080/api/plans/

Here is my Plan Model

var PlanSchema = new mongoose.Schema({
   title: {type: String},
   userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
   spots:[{
     name: {type: String},
     category: {type: String},
     address: {type: String},
     hours: {type: String},
     phone: {type: String},
     website: {type: String},
     notes: {type: String},
     imageUrl: {type: String},
     dayNumber: {type: Number}
   }]
});

Here is my Plans Route.

    PlansController.get('/', function(req, res){
  Plan.find({}, function(err, plans){
  res.json(plans);
  });
});

PlansController.get('/:id', function(req, res){
  Plan.findOne({_id: req.params.id}, function(err, plan){
    res.json(plan);
  });
});


PlansController.get('/search', function(req, res){
  Plan.find({ userId: req.query.userId }, function (err, plans){
    res.json(plans);
  });
});

What am I doing wrong? In the terminal I get this,

GET /api/plans/search?userId=56bd16761e6bb0e5b2b43c9b 200 7.047 ms - -

Upvotes: 0

Views: 520

Answers (1)

manutdfan
manutdfan

Reputation: 295

I think I figured it out. since search route looks similar to /:id route, it keeps thinking of search strings as IDs and keeps using the id route. Search Route has to be included before the /:id route.

Here is the updated code.

PlansController.get('/search', function(req, res){
  console.log(req.query.userId);
  Plan.find({ userId: req.query.userId }, function (err, plans){
    console.log(plans);

    res.json(plans);
  });
});

PlansController.get('/:id', function(req, res){
  Plan.findOne({_id: req.params.id}, function(err, plan){
    res.json(plan);
  });
});

Upvotes: 1

Related Questions