mongodb ObjectId is treated differetly

2019-03-05 23:14发布

I tried to query on a document using $in and passing an array of Ids.

On this test I got the values intended.

Document.find({
    documentId: {
        $in: ['598eb5a9957d7427f41d7f08',
            '5a5d863cf9d4d74f2b3d3180'
        ]
    }
}).then(data => {
    console.log(data);
});

But when using this, I am just getting an empty result.

Document.aggregate([{
    $match: {
        documentId: {
            $in: ['598eb5a9957d7427f41d7f08',
                '5a5d863cf9d4d74f2b3d3180'
            ]
        }
    }
}]).then(data => {
    console.log(data);
});

I am able to fixed it if I will convert the id explicitly to ObjectId.

Document.aggregate([{
    $match: {
        documentId: {
            $in: [
                new mongoose.Types.ObjectId(
                    '598eb5a9957d7427f41d7f08'
                ),
                new mongoose.Types.ObjectId(
                    '5a5d863cf9d4d74f2b3d3180'
                )
            ]
        }
    }
}]).then(data => {
    console.log(data);
});

Any advice why this is happening?

I want to omit that query on the last code on converting the objectId.

Thanks.

1条回答
The star\"
2楼-- · 2019-03-06 00:03

Mongoose's docs state that pipeline stages are handled like native pipeline stages, ergo: You have to cast you id's to ObjectIds.

http://mongoosejs.com/docs/api.html#Aggregate

Note:

  • The documents returned are plain javascript objects, not mongoose documents (since any shape of document can be returned).
  • Mongoose does not cast pipeline stages. The below will not work unless _id is a string in the database

    new Aggregate([{ $match: { _id: '00000000000000000000000a' } }]);
    // Do this instead to cast to an ObjectId
    new Aggregate([{ $match: { _id: mongoose.Types.ObjectId('00000000000000000000000a') } }]);
    
查看更多
登录 后发表回答