Search code examples
node.jsexpressmongoosemongoose-schemamongoose-populate

Mongoose .populate() returning an empty array


I'm sorry, I know there are a lot of questions asking this same thing, but I can't find any answers that solve it for me!

I'm trying to use a mongoose populate function to populate the ID of a schema, but it just returns an empty array. The ID's are in the array if I don't use the populate function, but using it seems to delete them.

My routes and models are simple as I'm just trying to learn it, which is more confusing as to why it's wrong! And I thought I followed the tutorial thoroughly....

These are my schema's:

var SeasonSchema = new Schema(
  {
    name: {type: String, required: true, enum: ['Spring', 'Summer', 'Autumn', 'Winter']},
    description: {type: String, maxLength: 300}
  }
);
var FruitSchema = new Schema(
  {
    name: {type: String, required: [true, 'All fruits have names.'], maxLength: 50},
    description: {type: String, maxLength: 300},
    season: [{type: Schema.Types.ObjectId, ref: 'Season', required: true}],
    price: {type: Number, min: 0, max: 9.99, required: true},
    stock: {type: Number, min: 0, max: 999, required: true}
  }
);

And this is the controller I'm trying to get to work: (Simply populating the Fruit's Season field.

exports.fruit_detail = function(req, res, next) {
    Fruit.findOne({name: req.params.name})
    .populate('season')
    .exec(function (err, fruit) {
      if (err) {return next(err);}
      if (fruit==null) {
        var err = new Error('Fruit not found');
        err.status = 404;
        return next(err);
      }
      res.render('fruit_detail', {title: fruit.name, fruit: fruit});
    });
};

Thank you for any help. I'm at my wits end.


Solution

  • Massive face palm emoji.

    The problem was the season ID's being referenced were from non-existent seasons. I'd somehow made duplicates when populating the database, and I'd deleted the wrong ones. Feel like I wasted two days of my life, but at least it's sorted!