2015-05-04 104 views
0

我在MEAN堆栈上构建了一个相当简单的应用程序,而且我真的超出了我的深度,尤其是涉及猫鼬的时候。我发现猫鼬的文件很难缠绕我的头,无法在其他地方找到答案。我的问题是这样的:我有一堆用户,这些用户有仓库,仓库有仓库提供者(GitHub,BitBucket等)。Mongoose'populate'not populating

用户拥有多个存储库并且存储库具有一个存储库类型。

我的用户文件包含以下内容:

var mongoose = require('mongoose'), 
Schema = mongoose.Schema; 

var UserSchema = new Schema({ 
    name: { 
     type: String, 
     required: true 
    }, 
    email: { 
     type: String, 
     required: true 
    }, 
    repositories: [{ 
     name: String, 
     branches: [{ 
      name: String, 
      head: Boolean, 
      commits: [{ 
       hash: String, 
       date: Date, 
       message: String, 
       contributer: String, 
       avatar: String 
      }] 
     }], 
     repoType: { 
      type: Schema.Types.ObjectId, 
      ref: 'RepoProviders' 
     } 
    }] 
}); 

var User = mongoose.model('User', UserSchema); 

module.exports = User; 

// This is where the magic doesn't happen :(

User.find({ name: "John Smith"}).populate({path: 'repoType'}).exec(function (err, user) { 
    if (err) return handleError(err); 
    console.log(user); 
}); 

RepoProvider.js包含:

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

var RepoProviderSchema = new Schema({ 
    name: { 
     type: String, 
     required: true 
    } 
}); 

var RepoProvider = mongoose.model('RepoProviders', RepoProviderSchema); 
module.exports = RepoProvider; 

我创造了蒙戈用户文档和手动分配repoType ID散(从现有的repoType采取文件)。

当我CONSOLE.LOG用户,回购类型设置为ID,但没有关系返回:

[ { _id: 5547433d322e0296a3c53a16, 
    email: '[email protected]', 
    name: 'John Smith', 
    __v: 0, 
    repositories: 
    [ { name: 'RepoOne', 
     repoType: 5547220cdd7eeb928659f3b8, 
     _id: 5547433d322e0296a3c53a17, 
     branches: [Object] } ] } ] 

如何正确设置和查询这种关系?

回答

1

你需要指定在populate方法的完整路径repoType

User.find({ name: "John Smith"}).populate({path: 'repositories.repoType'}).exec(function (err, user) { 
    if (err) return handleError(err); 
    console.log(user); 
}); 
+0

哦,伙计......你知道多久,我都花在这个?结果就是这个! Ugggh ...我准备好运行回PHP的尖叫。非常感谢您的帮助! – nickspiel

+0

:D Mongoose可能会对稀疏文档有点混淆,但最近项目已经过渡,新的维护人员正在努力解决这个问题(还有很多其他事情)。 –

+0

啊好消息!通过完整的示例来获得简单的“入门指南”确实会有所帮助,但这些都不足以填补目前文档中出现的空白废话。 – nickspiel