I'm still trying to wrap my head around mongoDB/mongoose and haven't been able to workout what's wrong with the below query;
Link
.find()
.where('active').equals(true)
.where('access_count').gt(0).lte('access_limit')
.limit(5)
.sort('-created')
.exec(function(err,latest)
Which returns the below cast error;
CastError: Cast to number failed for value "access_limit" at path "access_count"
at SchemaNumber.cast
This is caused by the .where('access_count').gt(0).lte('access_limit') I assume it's due to the comparison of two fields on the document? Is there a correct way of doing this and any advice for debugging these kind of issues?
For reference the schema is defined as;
var LinkSchema = new Schema({
token: {type: String, unique: true, index: true, required: true }
, title: {type: String}
, url: {type: String, required: true}
, active: {type: Boolean, default: true}
, created: {type: Date, default: Date.now}
, access_count: {type: Number, default: 0}
, access_expiry: Date
, access_limit: {type: Number, default: 0}
})
To compare one field against another in a query, you have to use a $where clause:
Link
.find()
.where('active').equals(true)
.where('access_count').gt(0)
.$where('this.access_count <= this.access_limit')
.limit(5)
.sort('-created')
.exec(function(err,latest)
$where can be slow, so do as much as possible with normal where clauses to reduce the number of docs that $where needs to execute over.