Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

querying against ObjectIds with the $lt and $gt operators #2277

Closed
weisjohn opened this issue Sep 3, 2014 · 3 comments
Closed

querying against ObjectIds with the $lt and $gt operators #2277

weisjohn opened this issue Sep 3, 2014 · 3 comments

Comments

@weisjohn
Copy link

weisjohn commented Sep 3, 2014

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 + "')" } })
@vkarpov15 vkarpov15 added this to the 3.8.17 milestone Sep 8, 2014
@weisjohn
Copy link
Author

@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);
    })
})

@vkarpov15 vkarpov15 modified the milestones: 3.8.18, 3.8.17 Sep 29, 2014
@vkarpov15 vkarpov15 modified the milestones: 3.8.19, 3.8.18 Oct 22, 2014
@shrayolacrayon
Copy link
Contributor

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.

@vkarpov15 vkarpov15 removed this from the 3.8.19 milestone Nov 9, 2014
@reduxdj
Copy link

reduxdj commented Nov 7, 2017

this doesn't work for me

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants