0

I have a very simple DB model:

const MyModel = mongoose.Schema(
    {
        name: {type: String, unique: true, index: true}
    },
    {
        timestamps: {createdAt: 'createdAt'}
    }
);

And then one DB entry:

{name: 'TEST1, createdAt: '2017-10-19T08:15:52.443Z'}

When I run .find()

MyModel.find({createdAt: {$gte: moment('2017-10-19').toISOString()}}).exec();

I get search results as expected:

[
        {
            "_id": "59e85f38368dac5f372af352",
            "name": "TEST1",
            "createdAt": "2017-10-19T08:15:52.443Z",
            "__v": 1
        }
]

But when I use .aggregate()

MyModel.aggregate(
                {
                    $match: {
                        createdAt: {$gte: moment('2017-10-19').toISOString()}
                    }
                }
).exec()

It doesn't return anything

[]

What am I doing wrong?

emte
  • 647
  • 1
  • 8
  • 25
  • How is this duplicate? I'm not using objectIDs for my search criteria – emte Oct 19 '17 at 10:58
  • Aggregation pipelines in mongoose to not do "autocasting" which means looking at your schema and turning "strings" into the **correct** type that MongoDB is actually storing and expecting. In this case it's a `Date` object. The "skinny" is `moment('2017-10-19').toDate()` is what you should have been doing all along. Don't leave mongoose to clean up your mess and learn what the correct types are. – Neil Lunn Oct 19 '17 at 10:58
  • Thanks! I appreciate your advice :) – emte Oct 19 '17 at 11:00
  • See also https://github.com/Automattic/mongoose/issues/1399 which has some author notes on why there is no "autocasting" in mongoose aggregation pipelines, if actually reading the duplicate that does explain that is somehow not sufficient – Neil Lunn Oct 19 '17 at 11:00

0 Answers0