How can I query for docs where the message property length is less than 100?

Hi,

I have a collection where documents have a message property,
How can I query for docs where the message property length is less than 100?
I can not make the following work:

{$where: "this.message.length < 100"}

Thanks

You might just need to return it?

YourCollection.find({
  $where: 'function() { return this.message.length < 100 }'
})

I get the following error:
Exception while invoking method ‘words.getByPage’ MongoError: TypeError: this.message is undefined :

If the error says that “this.message” is undefined for some documents, then you should just update the $where function to account for documents where this.message is undefined. (Sorry if that sounds snarky, but sometimes the straightforward explanation is the correct one!)

Yes, but this time it is the mongo version that does not support $where operator.
I wonder How meteor sets the mongodb version?
I ended adding a length property that is calculated at the moment of insert or update and using that new property on queries.

This is incorrect, Mongo has supported the $where operator since 2.2 (likely earlier, but the docs don’t go back that far anymore) and Meteor has bundled mongo 2.2 or above since launch in 2012.

I just tested with 1.8.1 and it works perfectly:

> test = new Mongo.collection('test')
> test.insert({message: 'abcdefghijklmnop'})
> test.find({$where: 'function(){ return this.message.length > 3}'}).fetch()
[ { _id: 'GcggX4tS8jT6CyB5Q', message: 'abcdefghijklmnop' } ]
> test.find({$where: 'function(){ return this.message.length < 3}'}).fetch()
[]

Meteor bundles the best supported version of Mongo with each version of Meteor.
Which is Mongo 4.0.6 for Meteor 1.8.1

What @menewman meant here is if this.message is sometimes undefined (thus throwing an error when trying to access length) just test for the existence of message:

YourCollection.find({
  $where: 'function() { return this.message && this.message.length < 100 }'
})
2 Likes