1

everyone! I'm looking for a solution to my problems around the internet a few days and after a lot of failed tries, I decided to ask my first question here.

So, I have a model like this:

const Exercise = new Schema (
    {
        description: String,
        duration: Number,
        date: Date
    },
    {
        _id: false
    }
);

const User = new Schema({
    username: String,
    log: [
        Exercise
    ]
});

And I would like to find an specific user and filter his/her exercise log in a date range. If there isn't any exercise in the range, I'd just like to return the id, username and the log as an empty array. So, I've built this query:

User.aggregate([
        {
            $match: {
                _id: userIdInput
            }
        },
        {
            $project: {
                _id: 1,
                username: 1,
                log: { 
                    $filter: { 
                        input: "$log", 
                        as: "log", 
                        cond: { 
                            $gte: [ "$$log.date", from ]
                        } 
                    } 
                }
            }
        }])
        .exec()
        .then((log) => {
            res.json(log);
        })
        .catch(err => {
            next(err);
        });
       
}

But this query always return an empty array. Is there anything wrong I'm doing or any tips to compose this query in a better way?

I really appreciate any help.

  • 1
    What's your `from` data type? Is a string, date, number? It should be `Date` to compare values. I've tried [this](https://mongoplayground.net/p/d6wKydvANRd) and it seems to work ok. It is your query but using `ISODate("...")` instead of `from`. – J.F. Dec 11 '20 at 20:34
  • @J.F. Hey, I tried the link you sent and it really works. The `from` data type is Date and I'm using `toISOString()` on it. Anyways, it still won't work even if I compare `duration` for exemple. I'm begging to think that the problem is not the query, but it may not be compatible with Mongoose. – Rômulo Andrade Dec 15 '20 at 14:39

1 Answers1

0

Turns out the problem is that when we use aggregate() in mongoose, we must cast manually the id string to ObjectId type, since it doesn't do it automatically as in find() for example.

The resource: Moongoose aggregate $match does not match id's