How do you access attributes of an object queried from Mongo in Meteor

后端 未结 1 865
春和景丽
春和景丽 2021-01-19 10:19

I\'m pretty new to mongo in the Meteor.js framework. Here, I\'ve queried a MongoDB object using it\'s ID. I\'m trying to access an attribute \"mana\" but it returns me undef

1条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-19 10:44

    find method returns a cursor, not object nor array. To access object, you need to either fetch it from the cursor

    var skill = Skills.find(Session.get('selected_skill')).fetch()[0];
    

    or get it directly with findOne:

    var skill = Skills.findOne(Session.get('selected_skill'));
    

    Then you may use it just as any other js object:

    console.log(skill.mana);
    skill._cache = {cooldown: true};
    

     


     

    Keep in mind that on client-side, collection methods like find are non-blocking. They return whatever Meteor has in cache, not necessarily what is in the server-side db. That's why you should always use them in a reactive context, or ensure that all data has been fetched before execution (don't worry about the latter until you're fluent with Meteor, start with the first way).

    Also, you need to keep in mind that because of this, findOne and find.fetch may return null / empty array, even when the corresponding element is in db (but hasn't been yet cached). If you don't take that into account in your reactive functions, you'll run into errors.

    Template.article.slug = function() {
        var article = Articles.findOne(current_article);
        if(!article) return '';
        return slugify(article.title);
    };
    

    If we didn't escape from the function with if(!article), the expression article.title would raise an error in the first computation, as article would be undefined (assuming it wasn't cached earlier).

     


     

    When you want to update the database from client side, you can alter only one item by a time, and you must refer to the item by its _id. This is due to security reasons. Your line for this was ok:

    Skills.update(Session.get('selected_skill'), {$inc: {mana: 1}});
    

     


     

    alert() is a function that returns undefined no matter what you feed it.

    alert(42); // -> undefined
    

    Generally, it's far better to debug with console.log than with alert.

    0 讨论(0)
提交回复
热议问题