Search code examples
javascriptmongodbmongoosemongoose-schema

Pull a list of json objects with a Reference ID - MongoDB and Mongoose


Similar questions have been asked before but i have not been able to pull a workable solution out from the responses, so excuse my ignorance here. I am just learning this stuff.

I have a schema setup

let movieSchema = mongoose.Schema({
  Title:{type: String, required:true},
  description: {type: String, required:true},
  genre: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Genre'}],
  director: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Director'}],
  Actors: [String],
  imageUrl: String,
  featured: Boolean
});

Corresponding Genre Schema

let genreSchema = mongoose.Schema({
  name: {type: String, required: true},
  description: String
});

Then I am trying to use an endpoint and pull all movies that contain that genre ID. i get no errors just a blank result.

app.get('/movies/:genre',  passport.authenticate('jwt', {session:false}), (req, res) => {
  Movies.find({ genre:req.params.genre })
    .then((movies) => {
      res.status(201).json(movies);
    })
    .catch((err) => {
      console.error(err);
      res.status(500).send('Error: ' + err);
    });
});

For testing a request i would use something like /movies/609eab2d182950cee2ca2383

Thanks for the help!


Solution

  • So the working method is as follows.

    app.get('/movies/:genre',  passport.authenticate('jwt', {session:false}), (req, res) => {
      const genre = req.params.objectID;
      Movies.find({ 'genre.type':genre })
        .then((movies) => {
          res.status(201).json(movies);
        })
        .catch((err) => {
          console.error(err);
          res.status(500).send('Error: ' + err);
        });
    });
    

    And now it works!