Feature Request: Smarter queries #4873

QuotableWater7 opened this Issue Jan 4, 2017 · 7 comments


None yet

4 participants

QuotableWater7 commented Jan 4, 2017 edited

I would like to chat about possibly removing some boilerplate around queries, by accepting either an array of values or a single value for a given query key.

What is the current behavior?

someModel.find({ someKey: oneValue })

// OR

  someKey: { $in: arrayOfValues },

What is the desired behavior?

someModel.find({  someKey: oneValue })

// OR

someModel.find({ someKey: arrayOfValues })

I worked previously with ActiveRecord, and they had abstracted the difference between single value and an array of values into the ORM. It makes for slightly cleaner code, as the nested braces can be difficult to read on the same line. We often take a simple query and spread it across 3 lines just to avoid that.

I wanted to see if the mongoose maintainers would be open to this sort of feature -- if so, I am more than happy to write the code that can make this happen. I might have a question or two about the likely spots I'd need to hit, though.

Also, to clarify, this would be 100% backwards compatible.

Thanks for your time!

TrejGun commented Jan 5, 2017

good point for 5.0

QuotableWater7 commented Jan 6, 2017 edited

@TrejGun Just wanted to check in, are there any next-steps from my side (getting more decision-makers to take a look, submitting a PR, etc)? Thanks!

TrejGun commented Jan 11, 2017 edited

actually, looking at the code more close it seems you can use array operations with single element

howeven it will create a query like

{ _id: { '$in': [ ObjectId("5875a365589f0c2d29f0c2e6") ] } }

but not

{ _id: { '$eq': ObjectId("5875a365589f0c2d29f0c2e6") } }

which will cause performance issue

I'm pretty sure @vkarpov15 won't merge this in mongoose 4, so if you want to switch operator at runtime you probably should try to write a plugin


@TrejGun Correct me if I'm wrong, but I think your example is slightly different than I'm going for. I'm basically wanting to do:

{ _id: someVariableContainingArrayOfIds }

Whereas right now, I'm forced to expand out some boilerplate:

{ _id: { $in: someVariableContainingArrayOfIds } } 

Does that make sense?

@vkarpov15 vkarpov15 added this to the 4.9 milestone Jan 19, 2017

I really like this idea, definitely something to put in for a future release. Would you be interested in putting in a PR @QuotableWater7 ? I'd be happy to help, otherwise gonna have to wait until I start working on 4.9.


Cool, thanks for taking a look @vkarpov15! I would absolutely be happy to put together a PR -- I'll try and acquaint myself with the code tonight.


@vkarpov15 I opened a PR to get some feedback on the approach. Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment