Mongoose Aggregate:变量$ in数组中的ObjectId不返回true

问题描述 投票:1回答:1

myId是一个具有5dfe303c5eb482ec2672217d值的id,并且$amIinThisArray.userId也是5dfe303c5eb482ec2672217d,因此我希望imFollowing为true,但始终为false。

const myId = '5dfe303c5eb482ec2672217d';
const followers = await userModel.aggregate([
         { $addFields: {
            avatarId: '$followerData.shared.avatarId',
            fullName: '$followerData.shared.fullName',
            imFollowing: {
              $in: [ // <==== DoesMongoose support $in ??
                  myId, // <==== Does this variable need to be converted to some type??
                  '$amIinThisArray.userId',
              ],
          },
        },

[当我在MongoDB IDE中使用...测试时]

            "$addFields": {
                "avatarId": "$followerData.shared.avatarId",
                "fullName": "$followerData.shared.fullName"
                "imFollowing": {
                    "$in": [
                        new ObjectID("5dfe303c5eb482ec2672217d"),
                        "$amIinThisArray.userId"
                    ]
                },    
            }

它返回true!

为什么?

myId是否需要转换为某些特殊类型?

node.js mongoose aggregation-framework
1个回答
1
投票

您可以通过]将String id转换为ObjectId

let mongoose = require('mongoose');
   const objectId=mongoose.Types.ObjectId("5dfe303c5eb482ec2672217d");

现在您可以使用objectId

© www.soinside.com 2019 - 2024. All rights reserved.