我正在 MEAN 堆栈上构建一个相当简单的应用程序,但我真的超出了我的深度,尤其是在 mongoose 方面。我发现 mongoose 文档很难理解,并且在其他任何地方都找不到答案。
我的问题是:我有一堆用户,这些用户有存储库,而存储库有存储库提供者(GitHub、BitBucket 等)。
一个用户有许多存储库,而一个存储库具有一种存储库类型。
我的用户文件包含以下内容:
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;
我在 mongo 中创建用户文档并手动分配 repoType id 哈希(取自现有的 repoType 文档)。
当我 console.log 用户时,repo 类型设置为 id 但没有返回任何关系:
[ { _id: 5547433d322e0296a3c53a16,
email: 'john@smith.com',
name: 'John Smith',
__v: 0,
repositories:
[ { name: 'RepoOne',
repoType: 5547220cdd7eeb928659f3b8,
_id: 5547433d322e0296a3c53a17,
branches: [Object] } ] } ]
如何正确设置和查询这种关系?