Node.js 如何在mongoose中存在另一个文档的基础上获取文档?

Node.js 如何在mongoose中存在另一个文档的基础上获取文档?,node.js,mongodb,mongoose,nosql,Node.js,Mongodb,Mongoose,Nosql,我有一个名为post的集合,我有一个文档及其复制文档,但在复制文档中,我们有一个不同的字段,一些文档没有复制文档,这种情况取决于文档的数组字段,如果该字段的userId为user,则复制文档将存在,否则它将不存在 因此,如果doc数组具有该id,那么我想要的是复制的post,如果没有,那么是原始post 我已进行了查询,但在$cond中使用$exist时显示错误 Post.aggregate([ { $match: { so

我有一个名为post的集合,我有一个文档及其复制文档,但在复制文档中,我们有一个不同的字段,一些文档没有复制文档,这种情况取决于文档的数组字段,如果该字段的userId为user,则复制文档将存在,否则它将不存在

因此,如果doc数组具有该id,那么我想要的是复制的post,如果没有,那么是原始post

我已进行了查询,但在$cond中使用$exist时显示错误

Post.aggregate([
        {
            $match: {
                socomo_visibility: socomoId
            }
        },
        {
            $project: {
                "post_stream_type": {
                    $cond: {
                        if: {
                            'following_users_list': {
                                $exist: [userId]
                            }

                        },
                        then: constants.POST_STREAM_TYPE.FOLLOW.value,
                        else: constants.POST_STREAM_TYPE.SOCIAL_CURRY_CHANNEL.value
                    }
                }

            }
  }

                           ]

您可以通过以下方式检查数组在布尔表达式中是否具有某些值:

  • 使用进行数组和值的交集
  • 使用检查相交数组的大小
  • 如果大小大于0,则数组中存在值。我来检查一下
  • 请尝试以下代码:

    Post.aggregate([
      {
       $project: { 
        "post_stream_type": {
          $cond: { 
            if: {$gt: [{$size: {$setIntersection: ["$following_users_list", [userId]] } }, 0] }, 
            then: constants.POST_STREAM_TYPE.FOLLOW.value, 
            else: constants.POST_STREAM_TYPE.SOCIAL_CURRY_CHANNEL.value  
          } 
        }  
       }
      }
    ])
    

    好的,最后我在不使用聚合的情况下完成了这项工作。 我对这个问题的回答是

      Post.find({
        $or: [{
                socomo_visibility: {
                    $elemMatch: {
                        $eq: socomoId
                    }
                },
                post_stream_type: constants.POST_STREAM_TYPE.SOCIAL_CURRY_CHANNEL.value,
                following_users_list: {
                    $exists: true,
                    $nin: [userId]
                }
            },
            {
                socomo_visibility: {
                    $elemMatch: {
                        $eq: socomoId
                    }
                },
                post_stream_type: constants.POST_STREAM_TYPE.FOLLOW.value,
                following_users_list: {
                    $elemMatch: {
                        $eq: userId
                    }
                }
            }]
    })
    

    谢谢你的努力。我已经尝试过了,但是它返回了两个字段,其中包含所有数据的id和post\u stream\u name。如果原始文档arrray有userId,则需要获取该父id的post_stream_type:post_stream_type.FOLLOW.value,否则获取该父id的原始值。原始和复制的父id相同,但它们的流_type不同。