UNPKG

mingo

Version:

MongoDB query language for in-memory objects

35 lines (34 loc) 1.02 kB
import { assert, has } from "../../util"; import { applyUpdate, DEFAULT_OPTIONS, walkExpression } from "./_internal"; import { $set } from "./set"; const isIdPath = (path, idKey) => path === idKey || path.startsWith(`${idKey}.`); const $rename = (obj, expr, arrayFilters = [], options = DEFAULT_OPTIONS) => { const idKey = options.idKey; for (const target of Object.values(expr)) { assert( !isIdPath(target, idKey), `Performing an update on the path '${target}' would modify the immutable field '${idKey}'.` ); } const res = []; const changed = walkExpression( expr, arrayFilters, options, (val, node, queries) => { return applyUpdate(obj, node, queries, (o, k) => { if (!has(o, k)) return false; Array.prototype.push.apply( res, $set(obj, { [val]: o[k] }, arrayFilters, options) ); delete o[k]; return true; }); } ); return Array.from(new Set(changed.concat(res))); }; export { $rename };