【问题标题】:How to use $lookup if the localField is an array?如果 localField 是一个数组,如何使用 $lookup?
【发布时间】:2021-01-11 02:42:49
【问题描述】:

我有一个用户架构和一个帖子架构..用户架构有一个引用帖子架构的数组字段'posts',并且在用户架构中包含一个数组字段'followings'引用用户架构.. 这是用户架构

const UserSchema = new mongoose.Schema({
  name: {
    type: String,
    //required: true
  },
  email: {
    type: String,
    //required: true
  },
  dob: {
    type: Date,
    //required: true
  },
  username: {
    type: String,
    //required: true
  },
  posts :[
  {type: mongoose.Schema.Types.ObjectId,ref:'Post'}
],
  password: {
    type: String,
   // required: true
  },
  
  followers: [{
    type: mongoose.Schema.Types.ObjectId , ref:'User'
  }],
  following:  [{
    type: mongoose.Schema.Types.ObjectId , ref:'User'
  }]
    
});

和后期架构

const PostSchema = new mongoose.Schema({
    body: {
        type: String
    },
    topic: {
        type: mongoose.Schema.Types.ObjectId, ref: 'Topics'
    },
    title: {
        type: String
    },
    createdBy:{
        type: mongoose.Schema.Types.ObjectId, ref: 'User'
    
    },
     createdAt: {
        type: Date,
        default: Date.now()
     },
     comments:[{
        type: mongoose.Schema.Types.ObjectId , ref:'Comment' 
     }],
     updatedAt:{
         type: Date,
         default: Date.now()
     }
});

我被困在如何查询 mongoose 以获取他关注的所有用户帖子 怎么查询所有post用户的关注,谢谢

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

    使用聚合函数。

    1. 使用 $match 为用户过滤结果。
    2. $unwind "following" 字段(因为本地字段在下一阶段不能是数组)。
    3. 使用 $lookup 查找帖子
    4. 使用 $project 清理您的输出。

    解决方案应该是这样的(未测试):

    db.users.aggregate([
       {
          "$match":{
             "username":"user_username"
          }
       },
       {
          "$unwind":"$following"
       },
       {
          "$lookup":{
             "from":"posts",
             "localField":"following",
             "foreignField":"createdBy",
             "as":"posts"
          }
       },
       {
          "$project":{
             "posts":1,
             "following":1,
             "_id":0
          }
       }
    ])
    

    【讨论】:

      猜你喜欢
      • 2018-12-12
      • 2020-02-20
      • 1970-01-01
      • 1970-01-01
      • 2018-03-29
      • 1970-01-01
      • 2017-06-01
      • 2021-06-19
      • 1970-01-01
      相关资源
      最近更新 更多