猫鼬聚合:来自变量$ in的ObjectId数组未返回true

时间:2019-12-21 16:08:23

标签: node.js mongoose aggregation-framework

myId是一个ID,值为5dfe303c5eb482ec2672217d,并且$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是否需要转换为某些特殊类型?

1 个答案:

答案 0 :(得分:1)

您可以通过

将字符串ID转换为ObjectId。
let mongoose = require('mongoose');
   const objectId=mongoose.Types.ObjectId("5dfe303c5eb482ec2672217d");

现在您可以使用objectId