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:

{_id: "01",
  name: "Jimmy",
  canDrive: false }

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:

Template.profile.rendered = function() {
    if (<query>,<field> == true){
        $('.driving-tutorial').hide();
    else {
        $('.driving-tutorial').show(); }

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

var doc = Model.findOne({ canDrive: false });

will match this document

{
    _id: "01",
    name: "Jimmy",
    canDrive: false 
}

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:

Template.profile.rendered = function() {
    var doc = Model.findOne({ canDrive: false });
    if (doc && !doc.canDrive){
        $('.driving-tutorial').show();
    else {
        $('.driving-tutorial').hide(); 
    }
}

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:

Template.profile.rendered = function() {
    var doc = Model.findOne({ canDrive: false }),
        canDrive = (doc && !doc.canDrive);
    $('.driving-tutorial').toggle(canDrive);
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement