首页 > 解决方案 > 使用 _id 查找不适用于聚合

问题描述

我是 mongodb 的初学者,我正在尝试在 node.js 应用程序中使用 mongoose 编写查询:

const objectIdValue = secondId.valueOf();


  const existedRelation = await this.model.aggregate([
    { $match: { _id: firstId } },
    { $project: {
      relations: {
        $filter: {
          input: '$links',
          as: 'link',
          cond: {
            $and: [
              { $eq: ['$$link.target.entityId', `${objectIdValue}`] },
              { $eq: ['$$link.linkTypeId', linkTypeId] },
            ],
          },

        },
      },
    },
    },
  ]);
  console.log('existedRelation: ', existedRelation);

当我执行它时,我得到了这个结果:

existedRelation:  []

我尝试使用 mongoShell 执行它:

db.tasks.aggregate([
    { $match:{ _id: ObjectId("5bbf5800be37394f38a9727e") }},
    {
  $project: {
          relations:{
                $filter:{
                  input: '$links',
                  as: "link",
                  cond: {
                                  $and: [
                                  {$eq:["$$link.target.entityId", '5bbf52eabe37394f38a97276']},
                                  {$eq: ["$$link.linkTypeId", ObjectId("5bbf4bfcb075e03bd4a1b779")]}
                                  ]
                                  }

                }
              }
            }
          }

我得到了我想要的结果。我犯了什么错误?

标签: mongodbmongooseaggregation-framework

解决方案


Mongoose 不会强制String转换为ObjectId聚合函数。所以你必须使用猫鼬手动投射它。

var mongoose = require('mongoose')

const existedRelation = await this.model.aggregate([
  { "$match": { "_id": mongoose.Types.ObjectId(firstId) } },
  { "$project": {
    "relations": {
      "$filter": {
        "input": "$links",
        "as": "link",
        "cond": {
          "$and": [
            { "$eq": ["$$link.target.entityId", `${objectIdValue}`] },
            { "$eq": ["$$link.linkTypeId", linkTypeId] }
          ]
        }
      }
    }
  }}
])

推荐阅读