【问题标题】:Access an array in user Collection.[Meteor + React Native]访问用户集合中的数组。[Meteor + React Native]
【发布时间】:2018-10-27 00:56:51
【问题描述】:

我想返回保存在用户集合下的完整数组 [votes]。 这是 JSON 结构

{
    "_id" : "pziqjwGCd2QnNWJjX",
    "createdAt" : ISODate("2017-12-21T22:06:41.930Z"),
    "emails" : [ 
        {
            "address" : "test@test.com",
            "verified" : false
        }
    ]
    "votes" : [ 
        {
            "ZyYZ4LDTaeWNMN9eE" : "yes"
        },
        {
            "DSHhkdsjkdhsddsqd" : "no"
        }
    ]
}

我怎样才能 console.log 那个数组?目标是在插入之前检查它是否存在。

【问题讨论】:

    标签: javascript arrays meteor


    【解决方案1】:

    我假设您从 MongoDB 的集合中只返回 1 个文档。

    var user = Users.findOne({_id: your_given_id});
    
    if(user && user.votes && user.votes.length){
        console.log(user.votes);
        return user.votes;
    }
    console.log('No Votes Found.');
    return [];
    

    【讨论】:

      【解决方案2】:

      如果你只是想检查数组是否存在并且有元素:

      const user = Meteor.users.findOne(userId);
      const hasVotes = user && user.votes && typeof(user.votes) === 'object' && user.votes.length;
      

      【讨论】:

      • 注意:findOne() 返回单个对象,而服务器上的 find().fetch() 或 find() 返回数组
      • .find() 返回一个光标,而不是一个数组
      • 对不起!在反应本机查找返回数组。在流星返回光标
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-01
      • 2015-02-02
      • 1970-01-01
      • 2015-09-22
      • 1970-01-01
      相关资源
      最近更新 更多