【问题标题】:MongoDB / Mongoose - FindOneById with conditions. Match value of Array within Object thats within an ArrayMongoDB / Mongoose - 带有条件的 FindById。匹配数组内对象内数组的值
【发布时间】:2022-07-10 21:57:29
【问题描述】:

我知道这个问题的标题很拗口,但如果我提供一个例子,我希望你能明白我的意思。

这是我的 MongoDB 结构:

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

我想要做的是检查是否有具有某个 deviceId 的访问者。如果有一个我什么都不想做,但如果没有一个我想添加一个新访客。

这是我想在代码中做的:

// 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";
}

所以基本上我想检查一个对象数组中的字符串是否存在于另一个数组中。

【问题讨论】:

    标签: javascript typescript mongodb mongoose findoneandupdate


    【解决方案1】:

    通过使用下面的查询匹配的记录将被返回,如果结果为空,可用于插入记录

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

    【讨论】:

    • 完美运行。非常感谢你!你帮了我很多:)
    猜你喜欢
    • 2021-04-20
    • 1970-01-01
    • 2013-04-06
    • 1970-01-01
    • 1970-01-01
    • 2017-04-18
    • 1970-01-01
    • 2020-10-23
    相关资源
    最近更新 更多