Date comparison (probably referencing) casting problem on object array inside document

Wow - I’m so sorry… I should have seen this and I didn’t… I’m truly sorry you’ve had this experience with the forums… You’re right tho - we should have responded… this is a failure. I know it’s probably too late now but please allow me to provide something toward a resolution.

So… diving into the issue… seems like the root of the problem is that you’re trying to compare a field (deleted_by.deleted_at) to another field (last_activity_date) directly in a query filter, like:

{ 'deleted_by.deleted_at': { $lt: '$last_activity_date' } }

I think the only, and probably best way to do this is in an aggregation pipeline, not in standard Mongoose .find() queries. That’s why you’re seeing that cast error… I’m pretty sure Mongoose is trying to interpret "$last_activity_date" as a literal string and trying to cast it to a date.

If you’re trying to keep it elegant and avoid an aggregation pipeline… well TBH, you’re kinda stuck… this type of “compare field A to field B within the same document” isn’t doable with a basic .find().

What you can do:

  • Use aggregation, despite the preference to not:
const inboxes = await Inbox.aggregate([
  {
    $match: {
      participants: user1Id, // assuming you've already got that
    }
  },
  {
    $match: {
      deleted_by: {
        $elemMatch: {
          user: user1Id,
          deleted_at: { $lt: "$last_activity_date" }
        }
      }
    }
  }
]);
  • Alternative if you really wanna stick to .find(): You’d need to do filtering in code after fetching… for instance, grab inboxes where the user is a participant and then filter manually in JS based on the comparison of deleted_at < last_activity_date.

But IMHO, the aggregation pipeline is cleaner and avoids over-fetching + post-processing in app code.

Once again, I’m really sorry we missed this one… and I hope you’re able to use this to fix the issue.