嗨,这是我的收藏品我只想将userId看成子编目数组,如果userId存在于子编目数组中而不是创建新收集返回相同的channelId。如果userId都不存在于subcriber数组中,那么创建新文档如何在数组中搜索userid。 这是我的收藏。
{
"_id" : ObjectId("58dd1013e973fc0004743443"),
"createdAt" : ISODate("2017-03-30T14:02:59.175Z"),
"updatedAt" : ISODate("2017-03-30T14:02:59.175Z"),
"timestamp" : "2017-03-30",
"channelId" : "CH-EU7D",
"createdById" : "58dcc3cd9a7a301308b62857",
"message" : "",
"subcriber" : [
{
"userId" : "58dcc3cd9a7a301308b62857",
"channelId" : "CH-EU7D",
"_id" : ObjectId("58dd1013e973fc0004743444"),
"status" : "accepted"
},
{
"userId" : "58dcc3ec9a7a301308b62859",
"channelId" : "CH-EU7D",
"_id" : ObjectId("58dd1013e973fc0004743445"),
"status" : "pending"
}
],
"__v" : 0
}
我试过这个但没有用。
Channel.find({ 'subcriber.userId': b.userId }, { $and: [{ 'subcriber.userId': b.friendId }] }
答案 0 :(得分:1)
在nodejs中,您可以使用JavaScript Array.prototype.some()方法和json数组来测试是否有任何匹配的useId
,您需要编写如下内容:
function checkUserId(array, userId) {
return array.some(function(element) {
return userId === element.userId;
});
}
这是一个演示片段:
function checkUserId(array, userId) {
return array.some(function(element) {
return userId === element.userId;
});
}
var json = {
"_id": "58dd1013e973fc0004743443",
"createdAt": "2017-03-30T14:02:59.175Z",
"updatedAt": "2017-03-30T14:02:59.175Z",
"timestamp": "2017-03-30",
"channelId": "CH-EU7D",
"createdById": "58dcc3cd9a7a301308b62857",
"message": "",
"subcriber": [{
"userId": "58dcc3cd9a7a301308b62857",
"channelId": "CH-EU7D",
"_id": "58dd1013e973fc0004743444",
"status": "accepted"
},
{
"userId": "58dcc3ec9a7a301308b62859",
"channelId": "CH-EU7D",
"_id": "58dd1013e973fc0004743445",
"status": "pending"
}
]
};
//Check an existing userId
console.log(checkUserId(json.subcriber, "58dcc3ec9a7a301308b62859"));
//Check a non existing userId
console.log(checkUserId(json.subcriber, "58dcc3ec9a7a3000000000859"));

答案 1 :(得分:1)
对于这类问题可以使用$ elemMatch of mongodb。
db.getCollection('channels').find({subcriber:{"$elemMatch":{userId:"58dcc3cd9a7a301308b62857",userId:'58dcc3ec9a7a301308b62859'}}})