How can I query a Mongo collection using Mongoose to find all the documents that have a specific relation between two of their own properties?
For example, how can I query a characters
collections to find all those characters that have their currentHitPoints
value less than their maximumHitPoints
value? Or all those projects
that have their currentPledgedMoney
less than their pledgeGoal
?
I tried to something like this:
mongoose.model('Character')
.find({
player: _currentPlayer
})
.where('status.currentHitpoints').lt('status.maximumHitpoints')
.exec(callback)
but I am getting errors since the lt
argument must be a Number
. The same goes if I use $.status.maximumHitpoints
(I was hoping Mongoose would be able to resolve it like it does when doing collection operations).
Is this something that can be done within a Query? I would expect so, but can't find out how. Otherwise I can filter the whole collection with underscore
but I suspect that is going to have a negative impact on performance.
PS: I also tried using similar approaches with the find
call, no dice.
db.characters.find( "this.currentHitPoints < this.maxHitPoints" )
find({ 'status.currentHitpoints': { $lt: 'status.maximumHitpoints' } })
work?lt
method. But I found a solution and posted it below!