gpt4 book ai didi

node.js - MongoDB $lookup Objectid 得到空数组?

转载 作者:太空宇宙 更新时间:2023-11-03 23:24:59 25 4
gpt4 key购买 nike

我是 mongodb 新手,在 mongoose 以下文档中使用 $lookup 练习 aggregate ,我遇到了一个非常令人困惑的问题。

我有用户架构

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'
}])

但是我在查询中得到了空的common。根据db中的数据,我不应该得到这个结果。经过搜索我仍然找不到错误所在。

最后但并非最不重要的一点是,我需要使用aggregate方法,所以我必须在引用文档上使用$lookup,这有意义吗?

最佳答案

$lookup 中的 from 字段是集合名称,而不是模型变量名称。因此,如果您像这样初始化模型

db.model('User', userSchema)

那么查找查询应该是

commentModel.aggregate([{$lookup: {
from: 'users',
localField: 'author',
foreignField: '_id',
as: 'common'
}])

关于node.js - MongoDB $lookup Objectid 得到空数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45481049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com