Hello.
I’m using mongoose in Express and I need to add IDs to many objects inside of array inside of array. Assume that my schema looks like this:
{
_id: something,
property:value,
animals: [
{
dogs: [
{ name: 'Dog1' },
{ name: 'Dog2' }
],
cats: [
{ name: 'Cat1' },
{ name: 'Cat2' }
]
}
]
}
I want to achieve something like this:
{
_id: something,
property:value,
animals: [
{
dogs: [
{ name: 'Dog1', _id: uniqueID },
{ name: 'Dog2', _id: uniqueID }
],
cats: [
{ name: 'Cat1', _id: uniqueID },
{ name: 'Cat2', _id: uniqueID }
]
}
]
}
My code
db.collection('collectionName').updateMany(
{ animals: { $ne: [] } },
{
$set: {
'animals.$[].cats.$[]._id': mongoose.Types.ObjectId(),
'animals.$[].dogs.$[]._id': mongoose.Types.ObjectId()
}
}
);
It works but IDs are exactly the same. Now I know mongoose.Types.ObjectId() is a client-side function and it returns only once when running query so I have the same IDs in all objects.
How to achieve unique IDs?