APixel Visuals
APixel Visuals

Reputation: 1648

Mongoose - `CastError: Cast to number failed` when using "$fieldName"

I have the following Mongoose schema:

{
    lastEdit: Number
    translations: [{
      submittedTimestamp: Number
      ...
    }]
    ...
}

And the following query:

Model.findOne({
    "translations.submittedTimestamp": { $lte: "$lastEdit" }
})

However, I get an error saying CastError: Cast to number failed for value "$lastEdit" at path "submittedTimestamp" for model "translations".

If I plug in a static number instead of $lastEdit, in this case a Unix timestamp, the query works fine, which means that it has to do with the way I've used "$lastEdit". Any suggestions on how to fix this?

Upvotes: 1

Views: 257

Answers (1)

Ashh
Ashh

Reputation: 46451

You have to use $expr

Model.find({
  "$expr": {
    "$gte": [
      { "$size": {
        "$filter": {
          "input": "$translations",
          "cond": { "$lte": ["$$this.submittedTimestamp", "$lastEdit"] }
        }
      }},
      1
    ]
  }
})

Upvotes: 1

Related Questions