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

微笑、不失礼 提交于 2019-12-31 01:05:41

问题


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 undefined.

var skill = Skills.find({_id:Session.get("selected_skill")});
  alert(skill);//This returns me "undefined"
  Skills.update(Session.get("selected_skill"), {$inc: {mana: 1}});

Could you enlighten me on the requirements of accessing attributes in mongo for meteor? Thanks


回答1:


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.



来源:https://stackoverflow.com/questions/18711135/how-do-you-access-attributes-of-an-object-queried-from-mongo-in-meteor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!