簡體   English   中英

在Node.js中將現有對象查找到數組中

[英]Find existing object into an array in nodejs

嗨,這是我的收藏集,如果兩個userId都存在於subcriber數組中,我只想將userId放入subcriber數組中,而不是創建新的collection則返回相同的channelId。 如果兩個userId都不存在於用戶數組中,則創建新文檔,如何在數組中搜索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 }] }

在nodejs中,您可以對json數組使用JavaScript Array.prototype.some()方法來測試是否有匹配的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")); 

對於此類問題,可以使用mongodb的$ elemMatch。

db.getCollection('channels').find({subcriber:{"$elemMatch":{userId:"58dcc3cd9a7a301308b62857",userId:'58dcc3ec9a7a301308b62859'}}})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM