简体   繁体   English

MongoDB / Mongoose - 带有条件的 FindOneById。 匹配数组内对象内数组的值

[英]MongoDB / Mongoose - FindOneById with conditions. Match value of Array within Object thats within an Array

I know the title of this question is quite a mouthful but I hope you understand what exactly I mean if I provide an example.我知道这个问题的标题很拗口,但如果我提供一个例子,我希望你能明白我的意思。

This is my MongoDB structure:这是我的 MongoDB 结构:

{
   "_id":{
      "$oid":"62408e6bec1c0f7a413c093a"
   },
   "visitors":[
      {
         "firstSource":"123456",
         "lastSource":"",
         "email":"",
         "deviceIds":[
            "a7d5083e5c5df543a3e5b4db0742e866f554705353fae6fd6d30984d33c18ade"
         ],
         "_id":{
            "$oid":"624094328dd6ff9ac420c84a"
         }
      },
      {
         "firstSource":"123456",
         "lastSource":"",
         "email":"",
         "deviceIds":[
            "8972892x2sa3e5b4db0742e866f554705353fae6fd6d31892hdwif"
         ],
         "_id":{
            "$oid":"6240952c4d246158b74bb239"
         }
      }
   ]
}

What I want to do is check whether there is a visitor with a certain deviceId.我想要做的是检查是否有某个 deviceId 的访问者。 And if there is one I want to do nothing, but in case there isn't one I want to add a new visitor.如果有一个我什么都不想做,但万一没有一个我想添加一个新访客。

This is what I want to do in code:这就是我想在代码中做的事情:

// Find record based on ObjectID
const record = await UserRecord.findById(recordId);
// Check if the device id is already on the database within the record
if(record.visitors.deviceIds does not contain "certain deviceId") {
   // Add a new visitor inside of the visitor array
   record.visitors.deviceIds += "visitor with certain deviceId";
}

So basically I want to check whether a string inside of an array of an object that is inside of another array exists.所以基本上我想检查一个对象数组中的字符串是否存在于另一个数组中。

By using below query matched record would be returned which can be used to insert record if result is empty通过使用以下查询匹配的记录将被返回,如果结果为空,可用于插入记录

var result = UserRecord.find({
    "_id": recordId,
    "visitors.deviceIds": {
        "$elemMatch": {
            "$in": deviceId
        }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM