猫鼬填充文档
Mongoose populate documents
我在mongoose中得到了3个数据库模型,看起来像这样:
//profile.js
var ProfileSchema = new Schema({
username: { type: String, required: true },
password: { type: String, required: true },
matches: [{ type: Schema.Types.ObjectId, ref: 'Match' }]
});
//match.js
var MatchSchema = new Schema({
scores: [{ type: Schema.Types.ObjectId, ref: 'Score', required: true }],
});
//score.js
var ScoreSchema = new Schema({
score: {type: Number, required: true},
achivement: [{type: String, required: true}],
});
我尝试用
填充配置文件Profile.findOne({ _id: mongoose.Types.ObjectId(profile_id) })
.populate('matches')
.populate('matches.scores')
.exec(function(err, profile) {
if (err) {...}
if (profile) {
console.log(profile);
}
});
比赛被填充,但我没有得到比赛的分数来填充。这是不支持在猫鼬或我做错了什么?Populate给了我这个:
{
user_token: "539b07397c045fc00efc8b84"
username: "username002"
sex: 0
country: "SE"
friends: []
-matches: [
-{
__v: 1
_id: "539eddf9eac17bb8185b950c"
-scores: [
"539ee1c876f274701e17c068"
"539ee1c876f274701e17c069"
"539ee1c876f274701e17c06a"
]
}
]
}
但是我想在match数组中填充分数数组。我可以这样做吗?
是的,你是对的。我尝试使用链接填充,我得到相同的输出。
对于您的查询,请使用async.js,然后用下面提到的方法填充。
有关的更多详细信息,请查看此代码片段。这是一个工作,测试,样本代码根据您的查询。为了更好地理解下面的代码和提供的代码片段的链接,请仔细阅读注释的代码。
//Find the profile and populate all matches related to that profile
Profile.findOne({
_id: mongoose.Types.ObjectId(profile_id)
})
.populate('matches')
.exec(function(err, profile) {
if (err) throw err;
//We got the profile and populated matches in Array Form
if (profile) {
// Now there are multiple Matches
// We want to fetch score of each Match
// for that particular profile
// For each match related to that profile
async.forEach(profile.matches, function(match) {
console.log(match, 'match')
// For each match related to that profile
// Populate score achieved by that person
Match.find({
_id:match.id
})
.populate('scores', 'score')
.exec(function (err, score) {
if (err) throw err;
// here is score of all the matches
// played by the person whose profile id
// is passed
console.log(score);
})
})
}
});
Profile.findOne({ _id: mongoose.Types.ObjectId(profile_id) })
.populate('matches.scores')
.exec(function(err, profile) {
if (err) {...}
if (profile) {
console.log(profile);
}
});
相关文章:
- 正在对已提取的文档进行填充.有可能吗?如果有,怎么做
- 有没有一种方法可以找到一个匹配两个不同填充的文档,并在findOne()中获取他的文档
- 猫鼬在级联中填充嵌入式文档
- 如何填充子“引用”文档猫鼬数组
- 如何填充浏览器's用矩形显示的整个窗口/文档
- 我可以在mongoDB中找到基于填充条件的文档吗
- Mongoose如何填充引用的文档
- 是否有任何关于如何填充修订说明以及在什么条件下填充的文档
- 使用 JavaScript 模式填充文档
- 为什么不是文档.导致剪贴板填充的execCommand
- 在带有填充嵌套数组的mongoDB文档中查找并构建新的结果对象
- 如何附加点击事件在运行时,当我有一个数组中的所有id得到填充时,文档准备好了
- 填充有限数量的文档
- 猫鼬填充文档
- 如何在$geoNear之后填充子文档
- 我如何从模板节点复制并填充json数据,并用javascript将它们附加到文档中
- 向mongodb添加一个文档,并预先填充字符串的开始和结束
- 自动填充浏览器文档高度以滚动到任何元素
- Chrome中奇怪的文档正文右侧填充问题
- 在猫鼬中填充嵌入的文档