【问题标题】:How to filter a nested array in mongoose in a findOne without the nested object being required如何在不需要嵌套对象的情况下在 findOne 中过滤 mongoose 中的嵌套数组
【发布时间】:2020-09-08 09:25:22
【问题描述】:

我有一个名为选举的集合,在选举模式中有一个名为 votes 的嵌套数组。我正在尝试按 id 查询选举,并通过 userId 属性过滤嵌套的投票对象。我希望始终返回父选举对象,如果当前用户没有在选举中投票,votes 属性应该是一个空数组。

这是我的查询:

Election.findOne({
    _id: electionId,
    'votes.userId': userId
})
.exec()

问题在于,如果userId 没有任何投票,则也不会返回父 Election 对象。有什么方法可以过滤 votes 属性,但也不需要匹配父选举对象。

我来自 sql 的背景,在 Sequelize 中,我将如何做我想做的事情:

models.Election.findOne({
    where: {
        id: electionId
    }
    include: {
        model: models.Vote,
        where: {
            userId
        },
        required: false
    }
})

【问题讨论】:

    标签: node.js mongodb mongoose


    【解决方案1】:

    MongoDB 有一个$filter aggregation

    const res = await Election.aggregate([
      { $match: { _id: mongoose.Types.ObjectId(electionId) } },
      { $project: {
          _id: 1,
          votes: { $filter: {
            input: '$votes',
            as: 'userVote',
            cond: { $eq: [ '$$userVote', userId ] },
          }}
      }}
    ])
    

    相当于一个普通的js过滤器

    votes.filter(userVote => userVote.userId === userId)
    

    对此question on filtering arrays in mongodb 的其他一些答案也很相关,但那里的查询要求与您的问题略有不同,更像是您最初的尝试。

    【讨论】:

    • 这正是我想要的。非常感谢!
    猜你喜欢
    • 2023-01-19
    • 1970-01-01
    • 2020-02-01
    • 2019-10-22
    • 2018-04-27
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 2019-08-01
    相关资源
    最近更新 更多