【发布时间】:2014-08-13 01:30:21
【问题描述】:
我正在尝试使用 Show 模型中的数据填充()我的 User 模型中的所有订阅。我试过 .populate('subscriptions.show') 但它对结果没有任何影响。
如果我像这样将订阅设为一个普通的 Ref 数组
subscriptions: [{type: Schema.Types.ObjectId, ref: 'Show'}]
执行填充('subscriptions')按预期工作
我查看了在 Stackoverflow 上可以找到的所有类似问题以及在文档中可以找到的内容。我看不出我做错了什么。
我正在使用的完整测试文件源 https://gist.github.com/anonymous/b7b6d6752aabdd1f9b59
架构和模型
var userSchema = new Schema({
email: String,
displayName: String,
subscriptions: [{
show: {type: Schema.Types.ObjectId, ref: 'Show'},
favorite: {type: Boolean, default: false}
}]
});
var showSchema = new Schema({
title: String,
overview: String,
subscribers: [{type: Schema.Types.ObjectId, ref: 'User'}],
episodes: [{
title: String,
firstAired: Date
}]
});
var User = mongoose.model('User', userSchema);
var Show = mongoose.model('Show', showSchema);
初始数据
var user = new User({
email: "test@test.com",
displayName: "bill"
});
user.save(function(err, user) {
var show = new Show({
title: "Some Show",
overview: "A show about some stuff."
});
show.save();
user.subscriptions.push(show);
user.save();
});
查询
User.findOne({
displayName: 'bill'
})
.populate('subscriptions.show')
.exec(function(err, user) {
if (err) {
console.log(err);
}
console.log(user);
});
结果:
{
_id: 53a7a39d878a965c4de0b7f2,
email: 'test@test.com',
displayName: 'bill',
__v: 1,
subscriptions: [{
_id: 53a7a39d878a965c4de0b7f3,
favorite: false
}]
}
【问题讨论】:
-
那篇文章无法帮助我。也许我错过了你在那里看到的我的问题的答案。你能指出相关的部分吗?
-
这些链接都没有帮助。与我正在做的最接近的是:stackoverflow.com/questions/14594511/… 我已经尝试按照公认的答案所说的那样做。它没有影响。 .populate('subscriptions.show') 不会填充订阅数组上的 show 属性
-
不完全是重复的,因为它涉及更多一点。提供您想要的工作样本
标签: javascript node.js mongodb mongoose