Skip to content

Instantly share code, notes, and snippets.

@vadimshvetsov
Created May 25, 2017 11:56
Show Gist options
  • Save vadimshvetsov/1bd8fdc9a3a0163f88f8aeb7923913f0 to your computer and use it in GitHub Desktop.
Save vadimshvetsov/1bd8fdc9a3a0163f88f8aeb7923913f0 to your computer and use it in GitHub Desktop.
Function for merging objects in find*Update function with one level nesting.
/**
* 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;
@cbrhex
Copy link

cbrhex commented Jul 27, 2020

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