MongoDB $lookup Objectid 获取空数组? [英] MongoDB $lookup Objectid get empty array?

查看:37
本文介绍了MongoDB $lookup Objectid 获取空数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm new to mongodb and practice aggregate with $lookup in mongoose following document, And i met a question really confusing.

我有用户架构

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中的数据,我不应该得到这个结果.搜索后我仍然找不到是什么错误.

But i get empty common in the query. According to the data in db, I shouldn't get this result. After searching i still can not find what's the mistake.

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

Last but not least, I need to use aggregate method, so i have to use $lookup on reference document, dose it make sense?

推荐答案

$lookup 中的 from 字段是集合名称,而不是模型变量名称.所以如果你像这样初始化模型

The from field in $lookup is the collection name, not a model variable name. So if you are initializing the model like this

db.model('User', userSchema)

那么查找查询应该是

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

这篇关于MongoDB $lookup Objectid 获取空数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆