【问题标题】:How to get object in deeply nested array in mongoose using nodes如何使用节点在猫鼬的深度嵌套数组中获取对象
【发布时间】:2021-04-18 04:12:49
【问题描述】:

在我的用户集合中,我有以下内容

{
  _id: ObjectId('whatever user id'),
  movies: [
    {
      _id: ObjectId('whatever id of this movie'),
      name: 'name of this movie',
      actors: [
        {
          _id: ObjectId('whatever id of this actor'),
          name: 'name of this actor'
        }
      ]
    }
  ]
}

所以在我的用户集合中,我希望能够通过user.idpet.idactor.id 查询演员

我想像这样返回演员......

actor: {
  fields...
}

我尝试了以下...

const actor = await User.findById(req.user.id, {
  movies: {
    $elemMatch: {
      _id: req.params.movie_id,
      actors: {
        $elemMatch: {
          _id: req.params.actor_id,
        },
      },
    },
  },
});

我尝试了其他方法,但似乎无法正常工作。我看到您可以使用聚合,但我不知道如何在使用我可以使用的 ids 进行查询。

【问题讨论】:

    标签: arrays mongodb mongoose nested nodes


    【解决方案1】:

    我可以通过使用aggregate 来解决这个问题。我以前用过这个,但似乎我需要用mongoose.Types.ObjectId 转换我的ids,所以一个简单的req.user.id 不起作用。

    为了得到我的答案,我做了......

    const user = await User.aggregate([
      { $match: { _id: mongoose.Types.ObjectId(req.user.id) } },
      { $unwind: '$movies' },
      { $match: { 'movies._id': mongoose.Types.ObjectId(req.params.movie_id) } },
      { $unwind: '$movies.actors' },
      {
        $match: {
          'movies.actors._id': mongoose.Types.ObjectId(req.params.actor_id),
        },
      },
    ]);
    

    这没有返回以下格式的数据...

    actor: {
      fields...
    }
    

    但是像这样返回它......

    user: {
      movies: {
        actor: {
          fields...
        }
      },
      otherFields...
    }
    

    然后发回响应...

    res.status(200).json({
      status: 'success',
      data: {
        actor
      }
    })
    

    给出了我想要的格式。但是,我仍然想知道如何在不获取完整文档的情况下获取数据参与者

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-26
      • 2013-05-21
      • 2019-02-04
      • 2015-02-09
      • 1970-01-01
      • 2016-01-20
      • 1970-01-01
      • 2019-07-14
      相关资源
      最近更新 更多