Created
May 25, 2017 11:56
-
-
Save vadimshvetsov/1bd8fdc9a3a0163f88f8aeb7923913f0 to your computer and use it in GitHub Desktop.
Function for merging objects in find*Update function with one level nesting.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Consume update args object for document and can handle one level nesting. | |
* Returns object for leverage by $set in Mongoose update function. | |
* | |
* @param args | |
* @returns {{}} | |
*/ | |
const objectToDotNotation = (args) => { | |
const setObject = {}; | |
Object.keys(args).forEach((key) => { | |
if (typeof args[key] === 'object') { | |
Object.keys(args[key]).forEach((subkey) => { | |
setObject[`${key}.${subkey}`] = args[key][subkey]; | |
}); | |
} else { | |
setObject[key] = args[key]; | |
} | |
}); | |
return setObject; | |
}; | |
module.exports = objectToDotNotation; |
You can use just Object.assign(myNestedObject)
this.catModel.findOneAndUpdate(
{user: userId},
{$set: Object.assign(myNestedObject)}
);
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This would work indefinitely, but I don't know for sure how the $set update works.