猫鼬不是在生产(Heroku)上填充(.populate()),而是在本地工作



本质上,我正在经历这样的时刻之一。我的应用程序在Heroku上,它使用的数据库是mLab(MongoDB)。

  • 它适用于本地(Cloud9),但不适用于生产环境(Heroku)。
  • 我无法让 .populate() 用于生产。

您是否在下面的代码(片段)中看到任何可能导致 Heroku 失败的空白,而它在本地工作?

谢谢。

我尝试清除数据库(删除数据库并创建一个新数据库。我也在这个网站上有类似的问题。我也尝试了"heroku local --tail"命令来调试并在本地机器上运行它;它适用于本地...只是不在希罗库;出现错误。

 People.find(id).populate("friends").exec(function(err, user){
        if(err){
            console.log("! Error retrieving user. " + err);
            reject ("! Error retrieving user. " + err);
        }
        else {
            console.log("0! Friends should be populated: " + user);
            resolve(user);
        }
    });

我的模型:

var mongoose = require('mongoose');
var personSchema = mongoose.Schema({
    name: String,
    friends: [    
        {
            id: {
                type: mongoose.Schema.Types.ObjectId,
                ref: "Person"
            },
            name: String
        }
    ],
    username: String,
    password: String,
    });
module.exports = mongoose.model("Person", personSchema);

您的 API 函数看起来不错。

我怀疑您的问题在于模型的设置方式或数据库中的内容。当我第一次尝试使用Heroku时,我遇到了类似的问题,因为Localhost更宽容。

为了使您的 API 正常工作,必须设置以下 3 件事:

(1) Model file: people.js

必须看起来像这样:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var peopleSchema = new Schema({
  name: {
    type: String,
    required: true,
    trim: true
  },
  friends: [{
    type: Schema.Types.ObjectId,
    ref: "Friends"
  }]
});
const People = mongoose.model('Peoples', peopleSchema);
module.exports = People;

然后你必须有一个"朋友"模型,即"人"所指的模型。

(2) Model file: friends.js

必须看起来像这样:

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
// Create the Comment schema
var friendsSchema = new Schema({
  friend_name: {
    type: String,
    required: true,
    trim: true
  },
});
const Friends = mongoose.model('Friends', friendsSchema);
module.exports = Friends;

最后,为了.填充工作,数据库中至少需要两个文档。

(3) Database must contain a Person doc and a Friend doc 

必须看起来像这样:

people.js : 
    "_id": {
            "$oid": "5bef3480f202a8000984b3c5"
    }, 
    "name": "Monica Geller"
    "friends": [
        {
            "$oid": "5bef3480f202a8000984b5b4"
        }
    ]
friends.js :
    "_id": {
            "$oid": "5bef3480f202a8000984b5b4"
    },
    "friend_name": "Rachel Green"

希望这有所帮助,或者让您更接近答案。

这是一个版本问题。

必须确保所有平台(mLab和我的本地数据库)都使用相同的Mongoose版本。

npm install mongoose@5.4.8 --save 

最新更新