【问题标题】:Mongoose FindOne - only return fields which match conditionMongoose FindOne - 仅返回符合条件的字段
【发布时间】:2021-03-24 08:45:52
【问题描述】:

我正在尝试查询我的匹配(游戏)集合,并查找某个用户是否已将数据发送到“reportMessages”对象数组。

const results = await Match.findOne({ 'users': req.params.userIdOfReportSender, '_id': req.params.matchId, 'reportMessages.sentBy': req.params.userIdOfReportSender }, 'reportMessages' )

但是,上面的查询返回以下内容:

{
  _id: 5fd382c65d5395e0778f2f8a,
  reportMessages: [
    {
      _id: 5fd610f27ae587189c45b6ca,
      content: 'jajatest',
      timeStamp: 2020-12-13T13:02:42.102Z,
      sentBy: 'XbVvm6g3nsRmPg3P1pBvVl84h6C2'
    },
    { sentBy: "'anotheruser123" }
  ]
}

我怎样才能让它只返回第一个reportMessage,即XbVvm6g3nsRmPg3P1pBvVl84h6C2发送的那个?

Mongoose findOne 文档 (https://mongoosejs.com/docs/api.html#model_Model.findOne) 表明您可以提供参数来说明要选择哪些字段(在他们的情况下为“名称长度”,但没有显示仅在匹配特定条件的情况下选择字段的方法.

这甚至可能吗?尝试谷歌搜索这个看似简单的问题很长一段时间没有成功

亲切的问候

【问题讨论】:

    标签: database mongodb mongoose nosql conditional-statements


    【解决方案1】:

    您可以使用此聚合查询仅获取所需的子文档:

    Match.aggregate([
        {
            $match: { _id: req.params.matchId }
        },
        {
            $project: {
                reportMessages: {
                    $filter: {
                        input: '$reportMessages',
                        as: 'msg',
                        cond: { $eq: ['$$msg.sentBy', req.params.userIdOfReportSender] }
                    }
                }
            }
        },
        {
            $project: {
                reportMessage: { $arrayElemAt: [ '$reportMessages', 0 ] },
            }
        },
        { $replaceWith: '$reportMessage' }
    ]);
    

    请注意,您只需指定文档_id 即可获得单个结果,因为_ids 是唯一的。

    【讨论】:

    • 谢谢。在 $match 条件中将 ObjectId 包裹在 req.params.matchId 之后,它起作用了。仍然不确定为什么必须为此聚合查询执行此操作,但是例如在“updateOne”操作中,我不必将 ObjectId 包裹起来,并且可以继续使用 req.params.matchId 值(我相信它是一个字符串)。
    猜你喜欢
    • 2017-08-18
    • 2018-06-09
    • 1970-01-01
    • 2016-10-08
    • 2016-07-14
    • 2018-07-07
    • 2015-04-30
    • 2018-08-07
    • 1970-01-01
    相关资源
    最近更新 更多