Mongoose: querying against ObjectIds with the $lt and $gt operators

Created on 3 Sep 2014  ·  3Comments  ·  Source: Automattic/mongoose

Assuming a Schema with a normal _id property, I want to query with a $gt operator. Equivalent MongoDB query:

db.applications.find({ _id : { $gt : ObjectId("53ddb3c00000000000000000") } })

But, on the mongoose side, when using an object with the ObjectId type, it throws:

var minimumObjectId = new mongoose.Schema.ObjectId(minimumObjectIdString);
Applcation.find({ _id : { $gt : minimumObjectId } }) 
/*
{ [CastError: Cast to ObjectId failed for value "ObjectId('53de7ea3000000000000000')" at path "_id"]
  message: 'Cast to ObjectId failed for value "ObjectId(\'53de7ea3000000000000000\')" at path "_id"',
  name: 'CastError',
  type: 'ObjectId',
  value: 'ObjectId(\'53de7ea3000000000000000\')',
  path: '_id' }
*/

As does a simple String:

Application.find({ _id : { $gt : minimumObjectIdString } })

I've even tried something crazy like:

Application.find({ _id : { $gt : "ObjectId('" + minimumObjectIdString + "')" } })

Most helpful comment

this doesn't work for me

All 3 comments

@vkarpov15 , I think this may also be a problem in the underlying mongo-native-driver, as I tried to do something like:

Application.collection.find({ _id : { $gt : "53f0c1850000000000000000" } }, function(err, cursor) {
    console.log(err)
    cursor.toArray(function(results){
        console.log(results);
    })
})

What are you doing to get minimumObjectIdString? You should use mongoose.Types.ObjectId instead of mongoose.Schema.ObjectId

var minimumObjectId = new mongoose.Types.ObjectId(minimumObjectIdString);
Applcation.find({ _id : { $gt : minimumObjectId } }) 

It should work with a string as well.

this doesn't work for me

Was this page helpful?
0 / 5 - 0 ratings