0

I have the following Schema:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

// Create Schema
const StatsSchema = new Schema({

  CustomStat: {
    type: [{ Name: { type: String }, Value: { type: String }, Sport: { type: String } }],
    default: [{ Name: "Position", Sport: "Football" },
      { Name: "Age", Sport: "Football" },
      { Name: "Weight", Sport: "Football" },
      { Name: "Height", Sport: "Football" },
      { Name: "Speed", Sport: "Football" },
      { Name: "Bench", Sport: "Football" },
      { Name: "VJump", Sport: "Football" },
      { Name: "BJump", Sport: "Football"},
      { Name: "3-point Accuracy", Sport: "Basketball"}]
  }


});

// Create collection and add schema
mongoose.model('stats', StatsSchema, 'stats');

What I want to do is filter the CustomStat array and call something like findOne() where the CustomStat.Sport = "Basketball".

After I do that, the only value that should be passed through is { Name: "3-point Accuracy", Sport: "Basketball"}.

I have the following code:

Stats.find({ CustomStat: { $elemMatch: { Sport: 'Basketball' } } })
  .then((stats) => {
    res.render('records/displayrecords',
      {
        stats: stats
      });

  });

However, that code passes every single value in the array, even including where the Sport = "Football". What I want is for "stats" to be passed that only contains an array element where the Sport is Basketall.

Thank you in advance

Jas Singh
  • 29
  • 1
  • 8

1 Answers1

0

Try this one:

Stats.find({ "CustomStat.Sport": "Basketball"},{ $elemMatch: { Sport: 'Basketball' } })
  .then((stats) => {
res.render('records/displayrecords',
  {
    stats: stats
  });
});

Or visit this topic: Retrieve only the queried element in an object array in MongoDB collection

Hokage Sama
  • 83
  • 2
  • 11
  • The method you suggested gives me an error "Unsupported projection option: `$elemMatch:{Sport: "Basketball"}`. I tried `Stats.find({ "CustomStat.Sport": "Basketball" }, { CustomStat: { $elemMatch: { Sport: 'Basketball' } } })` which removed the error but still no help – Jas Singh Nov 30 '18 at 18:11
  • Edit: What you suggest does actually work :) which is progress. But I can't extract other values from it, only values that we filter are accessible. For example if I want to access the the id of stats by doing stats.id, it displays nothing. Is there any ways around that? – Jas Singh Nov 30 '18 at 18:43