首页 > 解决方案 > Mongoose FindOne - 仅返回符合条件的字段

问题描述

我正在尝试查询我的匹配(游戏)集合,并查找某个用户是否已将数据发送到对象的“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)表明您可以提供参数来说明要选择的字段(在他们的情况下为“名称长度”但不显示一种方法仅选择符合特定条件的字段。

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

亲切的问候

标签: databasemongodbmongoosenosqlconditional-statements

解决方案


您只能使用此聚合查询获取所需的子文档:

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 是唯一的。


推荐阅读