【问题标题】:MongoDB $lookup Objectid get empty array?MongoDB $lookup Objectid 得到空数组?
【发布时间】: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,这有意义吗?

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

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

    db.model('User', userSchema)
    

    那么查找查询应该是

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

    【讨论】:

    • 感谢您的回答,我已经编辑了我的问题,简而言之,我没有提到模型部分,但我确实创建了这些模型。
    • 根据更新的问题,集合名称应为usermodels。可以直接连接mongodb和show collections来验证
    • 感谢 sidgate。您指出了问题,我连接了 mongo shell 并使用 usermodels 而不是 userModel,它可以工作!但是在我早期的练习中,比如populate with reference,我选择了userModel,它也确实有效。无论如何,谢谢你的回答,它可以防止我发疯:)祝你有美好的一天!
    猜你喜欢
    • 2018-08-27
    • 2019-04-15
    • 1970-01-01
    • 2016-04-30
    相关资源
    最近更新 更多