MongoDb - Add object into array only if that object's id is not present in array object id.
Swaraj Jadhav
Developer | Educator | Innovator Contact : [email protected] | +918421946505
Use Case : Check schema, If you want to add new object into "data" array and you want to check if that new object's id is present or not in array, If present then add to data array, If not present then don't add.
Ex. You want to check your new object's id like "dataId" OBJ - { dataId : 5, dataIcon : "xyz" } matches with user 1 and data.someObj.dataId . If not found then you can add new obejct like this into data - { someObj : { dataId : 5, dataIcon : "xyz" } , description : { userName : "kkk", userData : "some data" } }.
Schema : Users
[ { _id : 1,
name : "raj",
data : [ { someObj : { dataId : 1, dataIcon : "xyz" } ,
description : { userName : "abc", userData : "some data" }
} ,
{ someObj : { dataId : 2, dataIcon : "xyz" } ,
description : { userName : "abc", userData : "some data" }
} , ]
} ,
{ _id : 2,
name : "alex",
data : [ { someObj : { dataId : 1, dataIcon : "xyz" } ,
description : { userName : "abc", userData : "some data" }
} ,
领英推荐
{ someObj : { dataId : 2, dataIcon : "xyz" } ,
description : { userName : "abc", userData : "some data" }
} , ]
}
]
const newObject = { dataId : 5 , description : "again somedata" }
JS Code -
const user = await Users.updateOne( {
? ? ? ? ? ? _id : userId,
? ? ? ? ? ? "data.someObj.dataId" : { $ne : newObject.dataId }
? ? ? ? }, {
? ? ? ? ? ? $push : {
? ? ? ? ? ? ? ? data : newObject
? ? ? ? ? ? }
? ? ? ? }, { upsert: true }).
Done.