juandemarco juandemarco - 1 year ago 83
Node.js Question

Mongoose Query: compare two values on same document

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

collections to find all those characters that have their
value less than their
value? Or all those
that have their
less than their

I tried to something like this:

player: _currentPlayer

but I am getting errors since the
argument must be a
. The same goes if I use
(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
but I suspect that is going to have a negative impact on performance.

PS: I also tried using similar approaches with the
call, no dice.

Answer Source

Thanks to Aniket's suggestion in the question's comments, I found that the same can be done with Mongoose using the following syntax:

        player: _currentPlayer
    .$where('this.status.currentHitpoints < this.status.maximumHitpoints')

Notice the $where method is used instead of the where method.

EDIT: To expand on Derick's comment below, a more performance sensitive solution would be to have a boolean property inside your Mongoose schema containing the result of the comparison, and update it everytime the document is saved. This can be easily achieved through the use of Mongoose Schema Plugin, so you would have something like:

var CharacterSchema = new mongoose.Schema({
    // ...
    status: {
        hitpoints: Number,
        maxHitpoints: Number,
        isInFullHealth: {type: Boolean, default: false}
.plugin(function(schema, options) {
     schema.pre('save', function(next) {
         this.status.isInFullHealth = (this.status.hitPoints >= this.status.maxHitpoints);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download