0

I'm creating a react app and I connected my backend mongo where I want to store all my car brands, year, models etc. In react I'm using the select tag and there I get everything that is in the db. DB running. However, whenever I press a specific car brand and try to pick the year with another select tag it shows me the years of all the other car brands. How can I do it so it only shows me years of that specific car brand? Should only show 2012.

My get function

carRoutes.route('/').get(function(req, res) {
    Car.find(function(err, car) {
        if(err) {
            console.log(err);
        } else{
            res.json(car);
        }
    }).collation().sort({car_description:1});
}); 

My Schema

let Car = new Schema({
    car_description: {
        type: String
    },
    car_year:{
        type: String
    }
});
MaZZa
  • 1
  • `Car.find()` will send back _everything_. You need to pass a query object `Car.find({ car_year : 2012 })` – Jeremy Thille Aug 26 '21 at 10:10
  • But this will only show me car brands from 2012. I only want it to filter whenever I select the specific car brand through the select tag. So for example if in my database I have Audi(2014), BMW(2012), Aud(2018), Mercedes(2020), and I press Audi in my select tagI will only get the years 2014, 2018 – MaZZa Aug 26 '21 at 10:16
  • Can you please link to sample data so we can understand this more clearly – Swapnil Soni Aug 26 '21 at 10:21
  • Does this answer your question? [Mongoose, Select a specific field with find](https://stackoverflow.com/questions/24348437/mongoose-select-a-specific-field-with-find) – ziishaned Aug 26 '21 at 10:56
  • Select your Audis with a distinct year : `find({car_description: 'Audi'}).distinct('car_year');` You'll get a list of years for Audi. – Jeremy Thille Aug 26 '21 at 11:24

1 Answers1

1

Try something like this (assuming car_description means the name):

Car.find({car_description: 'Audi'}).select('car_year -_id'); 
// you can replace 'Audi' with a variable which is assigned with the selected car name
Rukshan Jayasekara
  • 1,945
  • 1
  • 6
  • 26