【发布时间】:2018-04-14 14:15:39
【问题描述】:
我不明白为什么我的聚合管道未能合并多个集合(cmets 和用户)。我正在尝试返回 cmets 集合中每个 userId 的用户名。 MongoDB版本.... v3.0.7
.get(function(req,res){
//returning aggregate values from comments part.. comment.authorId must hv user.username.
CardComment.aggregate([ //stackoverflow qn... ask tomorrow show the models
//now perform the mongo join of multiple collections like in SQL Joins
{
$lookup:{
from: 'users', //external collection.
localField: 'authorId', //input field., from current collection.. cardComments
foreignField: '_id', //foreign key from external collection,
as: 'commentUser'
}
},
//filter according to the cardId.. part. find()... first pipeline
{
$match:{"card": req.params.cardId }
}
], function(err,comments){
if (err) {
res.json({"success":false, "message": 'Error in loading comments'})
} else {
//res.json({"success": true, "message": comments})
console.log(JSON.stringify(comments))
//console.log(comments) //u need to ask for help on stackoverflow.
}
})
})
对于我使用 mongoose 模块的 MongoDB 模式, 我已经缩短了它以使问题更小。 cardComments 集合架构
authorId:{
type: ObjectId,
ref : 'User',
required: true
},
createdAt: {
type: Date,
default: Date.now
}
然后用于用户集合。
var UserSchema = new Schema({
username: { type: String, required: true, lowercase: true, index: { unique: true } },
email: { type: String, required: true, index: { unique: true } },
//password: { type: String, required: true } u forgot the select field.. that z why login was disturbing
password: {type: String, select: false} //that z why u need postman to test stuff
});
我有兴趣在 cmets 集合的 authorId 部分显示用户集合中的用户名字段。 谢谢
【问题讨论】:
-
失败了怎么办?没有结果?
$lookup失败还是$match失败?您是否检查过以确保userId实际上与外部集合中的_id类型相同(通常两者都需要为ObjectId)。最常见的错误是一个存储为“字符串”,另一个存储为ObjectId。 -
在您的
comment架构中是card ObjectId吗?