Although the title of this question may be lengthy, I trust you grasp my meaning with an example.
This represents 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"
}
}
]
}
The goal is to determine if a visitor exists with a specific deviceId. If not, we aim to add a new visitor.
This is how to achieve it in code:
// Find record using ObjectID
const record = await UserRecord.findById(recordId);
// Check if device id already exists within the record's visitors
if(record.visitors.deviceIds does not contain "specific deviceId") {
// Add a new visitor to the visitor array
record.visitors.deviceIds += "visitor with certain deviceId";
}
To sum up, the objective is to verify the presence of a string inside an object's array nested within another array.