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
const update = {
$set: {
'resources.defs.icons': {
[md5(iconURL)]: {
persist: persist,
iconURL: iconURL,
iconName: _.get(iconData, 'iconName')
}
}
}
};
This is the result i prefer,
"resources": {
"defs": {
"icons": {
"c1b79846875970da7ee9cc5b1f9cc4ad": {
"persist": true,
"iconURL": "URL",
"iconName": ""
}
},
{
"28b569d3f9a3e63f94ca6fad969475f9": {
"persist": true,
"iconURL": "imageUrl",
"iconName": ""
}
}
}
}
If the object key exists update, if not insert a new key. This is how i achieved for an array,
const update = {
$addToSet: {
'resources.defs.icons': {
[md5(iconURL)]: {
persist: persist,
iconURL: iconURL,
iconName: _.get(iconData, 'iconName')
}
}
}
};
Now i need your help to achieve this for an object. Thank You!
You're very close to the solution, just need a little change:
const update = {
$set: {
[`resources.defs.icons.${md5(iconURL)}`]: {
persist: persist,
iconURL: iconURL,
iconName: _.get(iconData, 'iconName')
}
}
};
I found this solution,
const dynamicResourcePath = `resources.defs.icons.${md5(iconURL)}`;
const update = {
$set: {
[dynamicResourcePath]: {
persist: persist,
iconURL: iconURL,
iconName: _.get(iconData, 'iconName')
}
}
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.