我不知道为什么我的聚合管道无法组合多个集合(评论和用户)。我正在尝试返回评论集合中每个用户 ID 的用户名。MongoDB版本....3.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.
}
})
})
对于我的使用猫鼬模块的 MongoDB 模式,我缩短了它以使问题更小。卡片注释集合架构
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
});
我有兴趣在评论集合的 authorId 部分显示用户集合中的用户名字段。谢谢
如图所示,您使用的模式ObjectId
它应该是猫鼬对象 ID 像mongoose.Schema.Types.ObjectId
一样。那么$lookup
应该可以工作。另一件事如果cardId
也是ObjectId
那么您必须将其转换为猫鼬ObjectId
才能$match
阶段使用。如果cardId
在您的comments
架构中,则应首先使用$match
阶段来解决性能问题。
所以你的模型应该是这样的
authorId:{
type: mongoose.Schema.Types.ObjectId,
ref : 'User',
required: true
}
和您的函数
get(function (req, res) {
// if cardId is ObjectId type
let cardId = mongoose.Types.ObjectId(req.params.cardId);
CardComment.aggregate([
{
$match: {"card": cardId}
},
{
$lookup: {
from: 'users',
localField: 'authorId',
foreignField: '_id',
as: 'commentUser'
}
}
], function (err, comments) {
if (err) {
res.json({"success": false, "message": 'Error in loading comments'})
} else {
console.log(JSON.stringify(comments))
}
})
})
感谢您在检查$lookup运算符的错误消息时所做的努力。谢谢你的建议。 正如@Neil Lunn指出的那样,我应该检查我检查的错误消息,这似乎是数据库版本问题。$lookup在MongoDB 3.0.7中不受支持。 这是我检查它时遇到的错误。
{
"success": false,
"message": {
"name": "MongoError",
"message": "exception: Unrecognized pipeline stage name: '$lookup'",
"errmsg": "exception: Unrecognized pipeline stage name: '$lookup'",
"code": 16436,
"ok": 0
}
}