mongo-dot-notation
Version:
Transform objects to MongoDB update instructions
83 lines (82 loc) • 1.87 kB
TypeScript
/**
* Flatten options.
*/
export type Options = {
/**
* If true, arrays will be flattened and their indexes will be used as keys.
* @default false
* @example
* ```ts
* flatten({ rules: [{value: 7}] }, { array: true });
* // { $set: { 'rules.0.value': 7 } }
*
* flatten({ rules: [{value: 7}] }, { array: false });
* // { $set: { 'rules': [{value: 7}] } }
* ```
*/
array?: boolean;
/**
* If true, empty objects are ignored and removed from the flattened result.
* @default false
* @example
* ```ts
* flatten({ left: {x: 1}, right: {} }, { skipEmptyObjects: true });
* // { $set: { 'left.x': 1 } }
*
* flatten({ left: {x: 1}, right: {} }, { skipEmptyObjects: false });
* // { $set: { 'left.x': 1, 'right': {} } }
* ```
*/
skipEmptyObjects?: boolean;
};
/**
* Transforms a given object into the MongoDB's update instructions.
* @param value the input object to transform
*
* @example
* ```ts
* flatten({
* first_name: $rename('firstName'),
* lastName: 'Doe',
* updatedOn: $timestamp(),
* address: {
* primary: true
* },
* access: $push(new Date()),
* });
*
* // equivalent to:
* {
* "$rename": {
* "first_name": "firstName"
* },
* "$set": {
* "lastName": "Doe",
* "address.primary": true
* },
* "$currentDate": {
* "updatedOn": {
* "$type": "timestamp"
* }
* },
* "$push": {
* "access": new Date()
* }
* }
* ```
*
* @example
* ```ts
* // update arrays
* flatten({ scores: [{ value: 4 }, {value: 2}] }, { array: true} );
*
* // equivalent to:
* {
* "$set": {
* "scores.0.value": 4,
* "scores.1.value": 2,
* }
* }
* ```
*/
export declare const flatten: <T extends Record<string, any>>(value: T, options?: Options) => {};