从数组

时间:2016-05-28 14:36:12

标签: javascript arrays node.js mongodb meteor

我将Meteor与MongoDB一起使用,似乎无法弄清楚如何从对象数组中的对象访问单个字段。

我的文件:

  {
     "_id" : "p6c4cSTb3cHWaJqpG",
     "createdAt" : ISODate("2016-05-11T11:30:11.820Z"),
     "username" : "admin",
     "contacts" : [ 
         {
            "when" : ISODate("2016-05-11T11:30:32.350Z"),
            "who" : "4YBufbE9PByJBkasy"
         }, 
         {
            "when" : ISODate("2016-05-25T11:52:49.745Z"),
            "who" : "z792kEEYbxyzyEAKp"
         }, 
         {
            "when" : ISODate("2016-05-26T13:47:43.439Z"),
            "who" : "4YBufbE9PByJBkasy"
         }, 
         {
            "when" : ISODate("2016-05-26T13:48:22.828Z"),
            "who" : "4YBufbE9PByJBkasy"
         }
     ]
}

我想检查userId是否在任何对象中,特别是在who字段中。

我的服务器端代码:

 var me = Meteor.userId();
 var findMe = Meteor.users.findOne(me);

 if (_.include(findMe.contacts, {who: 4YBufbE9PByJBkasy})){
        console.log("found in array");
    }else{
        console.log("Not found in array");
    }
}

我尝试了几种不同的方式,但没有提出任何建议。

当我console.log(findMe.contacts);时,它会像它应该的那样返回整个数组。但是当我尝试console.log(findMe.contacts.who);时,它会返回undefined

就如何访问对象数组的字段需要一些指导。谢谢!

1 个答案:

答案 0 :(得分:1)

通过数组循环查看它是否包含值很容易 完成Array.prototype.some

var data = {
    "_id" : "p6c4cSTb3cHWaJqpG",
    "createdAt" : "2016-05-11T11:30:11.820Z",
    "username" : "admin",
    "contacts" : [
        {
            "when" : "2016-05-11T11:30:32.350Z",
            "who" : "4YBufbE9PByJBkasy"
        },
        {
            "when" : "2016-05-25T11:52:49.745Z",
            "who" : "z792kEEYbxyzyEAKp"
        },
        {
            "when" : "2016-05-26T13:47:43.439Z",
            "who" : "4YBufbE9PByJBkasy"
        },
        {
            "when" : "2016-05-26T13:48:22.828Z",
            "who" : "4YBufbE9PByJBkasy"
        }
    ]
};

var hascontact = function(contacts, id){
    return contacts.some(function(contact){
        return contact.who === id;
    });
};

console.log(hascontact(data.contacts,'4YBufbE9PByJBkasy'));
console.log(hascontact(data.contacts,'z792kEEYbxyzyEAKp'));
console.log(hascontact(data.contacts,'asdfasdfasdfasdfa'));