【发布时间】:2018-01-10 20:55:58
【问题描述】:
我是 mongodb 的新手,在 mongoose 以下文档中练习 aggregate 和 $lookup,我遇到了一个非常令人困惑的问题。
我有用户架构
const userSchema = new Schema({
userName: {type: String, index:{unique: true}},
password: String,
avatar: String
})
评论架构
const commentSchema = new Schema({
post: {type: Schema.Types.ObjectId, ref:'postModel'},
author:{type: Schema.Types.ObjectId, ref:'userModel'},
content: String,
createTime: Date
})
和型号commentModel= mongoose.model('commentModel', commentSchema)
userModel = mongoose.model('userModel', userSchema)
然后我做
commentModel.aggregate.([{$lookup: {
from: 'userModel',
localField: 'author',
foreignField: '_id',
as: 'common'
}])
但我在查询中很常见。根据 db 中的数据,我不应该得到这个结果。搜索后还是找不到问题所在。
最后但同样重要的是,我需要使用aggregate 方法,所以我必须在参考文档上使用$lookup,这有意义吗?
【问题讨论】: