Skip to content

Instantly share code, notes, and snippets.

@vadimshvetsov
Created May 25, 2017 11:56
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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;
@ghulamMustafaRaza
Copy link

function objectToDotNotation (args) {
	let setObject = {};
	let rec = (args, prefix) => {
  		prefix = prefix ? `${prefix}.` : ''
  		Object.keys(args).forEach((key) => {
    		if (typeof args[key] === 'object') {
				rec(args[key], `${prefix}${key}`)
    		} else {
      			setObject[`${prefix}${key}`] = args[key];
    		}
  		});
	}
	rec(args)
	return setObject
}

@rsomlette
Copy link

rsomlette commented Apr 15, 2020

This would work indefinitely, but I don't know for sure how the $set update works.

/**
 * Consume update args object for document and can handle infinite level nesting.
 * Returns object for leverage by $set in Mongoose update function.
 *
 * @param {Object|Array<Object>} args The object or array to  loop through
 * @param {String} prefix The prefix to fill the $set object
 * @returns {Object}
 */
const objectToDotNotation = (args, prefix = '') =>
	Object.keys(args).reduce((acc, key) => {
		if (typeof args[key] === 'object') {
			Object.assign(acc, objectToDotNotation(args[key], `${prefix}${key}.`));
		} else {
			acc[`${prefix}${key}`] = args[key];
		}

		return acc;
	}, {});

@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