[英]How can I find the instance of a user in this javascript user system codebase?
[英]Javascript .find() How can I find and return all user names?
我现在正在学习Meteor,并希望获得我尝试过的所有用户名: Meteor.users.find({}, {"name" : 1}).fetch()
及其许多变体。 我总是只在MongoDB中获得整个对象。 但是我只想获取所有干净的用户名! 那怎么可能? 我用谷歌搜索,但什么都不懂:(
您很亲密,至少在正确的轨道上。 这就是我要做的。
对于初学者, name
不是默认字段,通常将其放置在用户文档的profile
子文档中。 像这样:
{
"_id" : "FkYj9MkLY2TmcDf7w",
"emails" : [
{ "address" : "your@email.com", "verified" : false }
],
"profile" : {
"name" : "Bob Loblaw",
"position" : "Attorney at law"
}
}
仅供参考,为简洁起见,我在上面的示例中省略了典型的密码和与服务相关的详细信息。
要检索名称,请执行以下操作:
Template.yourTemplate.helpers({
'users': function() {
return Meteor.users.find({});
}
});
然后在模板中显示名称:
{{#each users}}
{{profile.name}}
{{/each}}
如果要在JavaScript中而不是模板中访问名称:
var users = Meteor.users.find({}).fetch();
_.each(users, function(user) {
if(user.profile.name)
console.log(user.profile.name);
});
因此,您通常可以使用点符号来访问文档字段:
Meteor.users.findOne({}).profile.name
请注意,通常最好在访问字段之前检查查询是否返回结果(如上所示)。
最后,有一种方法可以检索设置了名称的所有用户,并排除没有名称的用户。
Meteor.users.find({'profile.name': {$exists: true}})
最后要注意的一点是, 'profile.name'
用引号引起来,因为字段名称包含.
。 这也向您展示了如何在查询本身中使用点符号来访问子文档字段。
你近了 根据Meteor文档 ,find方法接受两个参数-选择器和选项对象。
要仅返回name属性,请执行以下操作:
Meteor.users.find({},{fields:{'name':1, _id: 0}}).fetch()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.