使用聚合操作查找_id时无法工作

6

我是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")]}
                                  ]
                                  }

                }
              }
            }
          }

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

11

Mongoose在聚合函数中不会将String转换为ObjectId,因此您需要使用Mongoose手动进行类型转换。

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] }
          ]
        }
      }
    }
  }}
])

OK,还应该转换linkTypeId的类型:{ "$eq": ["$$link.linkTypeId", mongoose.Types.ObjectId(linkTypeId)] } - Slim

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接