mingo
Version:
MongoDB query language for in-memory objects
32 lines (31 loc) • 831 B
JavaScript
import { has, intersection, isObject, unique } from "../../util";
import {
applyUpdate,
clone,
DEFAULT_OPTIONS,
walkExpression
} from "./_internal";
const $addToSet = (obj, expr, arrayFilters = [], options = DEFAULT_OPTIONS) => {
return walkExpression(expr, arrayFilters, options, (val, node, queries) => {
const args = { $each: [val] };
if (isObject(val) && has(val, "$each")) {
Object.assign(args, val);
}
return applyUpdate(
obj,
node,
queries,
(o, k) => {
const prev = o[k] ||= [];
const common = intersection([prev, args.$each]);
if (common.length === args.$each.length) return false;
o[k] = clone(unique(prev.concat(args.$each)), options);
return true;
},
{ buildGraph: true }
);
});
};
export {
$addToSet
};