Skip to content
Advertisement

How to query a field in MongoDB with a boolean value and return a boolean whether it’s true or false

Check my simple collection:

JavaScript

What I want to do once a document is found, is to manipulate a DOM and show a <div class="driving-tutorial> if the field canDrive value is false and hide it if the value is true

Like this in meteor:

JavaScript

Advertisement

Answer

You could implement this logic with the findOne() method which finds the first document that matches the selector/query object in the arguments. Thus you can call findOne() with a Mongo selector, which is an object that specifies a required set of attributes of the desired document to match a document. For example, this selector

JavaScript

will match this document

JavaScript

You can then use the above logic in your template function to check for the existence of a document and the field, also bearing in mind that findOne() will return null if it fails to find a matching document, which often happens if the document hasn’t been loaded yet or has been removed from the collection:

JavaScript

You can also use the jquery toggle() method’s second version which accepts a Boolean parameter. If this parameter is true, then the matched elements are shown; if false, the elements are hidden:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement