猫鼬用 Express 填充,不在生产中工作 (Heroku)

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

这是一个 MERN 应用程序,托管在 github 上,它在本地主机上完美 运行。不幸的是,它不适用于 Heroku。

问题是 API 请求,它必须 return 一个对象并填充一个 OID 数组(参见部门模型)。 API 请求有效。我正在从 MLab 获取数据,但它 不会 填充 ... 而是 returns: "surveys":[]

API 文件

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**
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;

调查模型

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;

已解决。

问题出在数据库中:ref OID 被之前的更新打乱了,所以当它试图填充时,Mongoose 找不到任何匹配的 OID。

解决方案: 我们必须清除并重新播种。当存在正确的 OID 引用时,此代码在本地主机和 Heroku 中按预期工作。