I need to operate something same as how $addtoset works for arrays in mongodb but for an object,Im adding dynamically generated objects to an object. The dynamic key is based on a string which will help to maintain a unique value so another key will not inserted with the same dynamic key.
i tried $set which actually updates
JavaScript
x
12
12
1
const update = {
2
$set: {
3
'resources.defs.icons': {
4
[md5(iconURL)]: {
5
persist: persist,
6
iconURL: iconURL,
7
iconName: _.get(iconData, 'iconName')
8
}
9
}
10
}
11
};
12
This is the result i prefer,
JavaScript
1
19
19
1
"resources": {
2
"defs": {
3
"icons": {
4
"c1b79846875970da7ee9cc5b1f9cc4ad": {
5
"persist": true,
6
"iconURL": "URL",
7
"iconName": ""
8
}
9
},
10
{
11
"28b569d3f9a3e63f94ca6fad969475f9": {
12
"persist": true,
13
"iconURL": "imageUrl",
14
"iconName": ""
15
}
16
}
17
}
18
}
19
If the object key exists update, if not insert a new key. This is how i achieved for an array,
JavaScript
1
12
12
1
const update = {
2
$addToSet: {
3
'resources.defs.icons': {
4
[md5(iconURL)]: {
5
persist: persist,
6
iconURL: iconURL,
7
iconName: _.get(iconData, 'iconName')
8
}
9
}
10
}
11
};
12
Now i need your help to achieve this for an object. Thank You!
Advertisement
Answer
You’re very close to the solution, just need a little change:
JavaScript
1
10
10
1
const update = {
2
$set: {
3
[`resources.defs.icons.${md5(iconURL)}`]: {
4
persist: persist,
5
iconURL: iconURL,
6
iconName: _.get(iconData, 'iconName')
7
}
8
}
9
};
10