Home > front end >  MongoDB / Mongoose - FindOneById with conditions. Match value of Array within Object thats within an
MongoDB / Mongoose - FindOneById with conditions. Match value of Array within Object thats within an

Time:03-28

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:

{
   "_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. 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. Do you get what I mean? In case you do not understand my question please let me know.

I would really appreciate your guys help on this. Ive been stuck with this for a few days now already and cant seem to figure it out. Kind regards, Noah

CodePudding user response:

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
        }
    }
});
  • Related