【问题标题】:Aggregating data from different Schemas, where one schema has array type object聚合来自不同模式的数据,其中一个模式具有数组类型对象
【发布时间】:2020-11-28 05:22:30
【问题描述】:

我有 2 个不同的架构(即用户、帖子),用户有一个对象,即追随者,它是数组数据类型,我正在尝试聚合来自用户的所有帖子,这些用户具有 req.user.id 或登录“Followers”数组中的用户ID。

这是用户架构:

followers: [

{
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "user",
  },
},]

这是我正在使用的获取请求:

try {

 const posts = await Post.aggregate([
   {
     $lookup: {
       from: "users",
       localField: "user",
       foreignField: "followers.user",
       as: "followers",
     },
   },{$match: {'followers.user' : req.user.id }}
])
res.json(posts);

这将返回:[ ] 作为输出

【问题讨论】:

    标签: javascript node.js mongodb mongoose mern


    【解决方案1】:
    followers: [
    
      {
        user: {
         type: mongoose.Schema.Types.ObjectId,
         ref: "user",
      },
    },]
    

    如果上面的字段关注者在 Post 模式中,

     const posts = await Post.aggregate([
     {
       $lookup: {
         from: "users",
         localField: "followers.user",  <- field relation in Post
         foreignField: "_id", <- field objectId in users maybe "_id" 
         as: "followers",
       },
     },{$match: {'followers.user' : req.user.id }}
     ])
    

    如果上面的字段关注者在用户模式中,

     const posts = await Post.aggregate([
     {
       $lookup: {
         from: "users",
         localField: "user",  <- field relation in Post
         foreignField: "_id", <- field objectId in users maybe "_id" 
         as: "user",
       },
       },{$match: {'user.followers.user' : req.user.id }}
     ])
    

    【讨论】:

    • 感谢您回答 Arif,这里的 follower.user 是 User 模式中的数组,而不是 Post 模式中的数组。 Post Schema 将“user”作为对象来存储 mongoose objectId。
    • 我不知道你想做什么,但如果帖子有“用户”,只需将 localField 连接到“用户”,并将外键连接到用户中的“_id”,我已经在上面更新了我的答案。
    • { $unset: [ "followers.password", "followers.followers", "followers.following" ] }, { $unwind : "$followers" } ,{$match: {'followers .username' : userFind.username }} } 这对我有用:)
    猜你喜欢
    • 2020-03-27
    • 1970-01-01
    • 2020-01-12
    • 2013-03-12
    • 1970-01-01
    • 1970-01-01
    • 2015-09-04
    • 2018-04-08
    • 2019-07-07
    相关资源
    最近更新 更多