繁体   English   中英

如果 localField 是数组,如何使用 $lookup?

[英]How to use $lookup if the localField is an array?

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

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 的所有用户帖子中,我如何查询所有用户的帖子,谢谢

使用聚合函数。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM