Search code examples
mongodbherokupopulate

Mongoose Populate with Express, not working in production (Heroku)


This is a MERN app, hosted on github, and it works perfectly on localhost. Unfortunately, it does not work on Heroku.

The issue is the API request, it must return an object and populate an array of OIDs (see Department Model). API request is working. I'm getting the data from MLab, but it doesn't populate... instead returns: "surveys":[]

API File

router.get('/department_data/:d_oid', function(req, res) {
     Department.findOne({_id: req.params.d_oid}).populate("surveys").exec(function(err,doc){
          if(err) throw(err)
          res.send(doc)
     })
});

Department Model

**Department Model**
var mongoose = require("mongoose");
var Schema = mongoose.Schema;

// Create the survey schema
var departmentSchema = new Schema({

  department_name: {
    type: String,
    trim: true,
    required: true
  },

  surveys: [{
    type: Schema.Types.ObjectId,
    ref: 'Surveys'
  }],

  participants: [{
    type: String
  }],

  create_date: {
    type: Date,
    default: Date.now
  },

  created_by: {
    type: Schema.Types.ObjectId,
    ref: 'Created_By'
  },
});

departmentSchema.index({ department_name: 1, created_by: 1}, {unique: true});

const Department = mongoose.model('Departments', departmentSchema);

module.exports = Department;

Survey Model

var mongoose = require("mongoose");
var Schema = mongoose.Schema;

// Create the survey schema
var surveySchema = new Schema({

  survey_name: {
    type: String,
    trim: true,
    required: true
  },

  questions: [{
      type: Schema.Types.ObjectId,
      ref: 'Questions'
  }],

  created_date: {
     type: Date,
     default: Date.now
  }
});

const Survey = mongoose.model('Surveys', surveySchema);

module.exports = Survey;

Solution

  • Solved.

    The problem was in the database: the ref OIDs got scrambled with a previous update, so when it was trying to populate, Mongoose couldn't find any matching OIDs.

    Solution: we had to purge and re-seed. When the correct OID references exist, this code works as expected in localhost & Heroku.