Skip to content

Instantly share code, notes, and snippets.

@szy0syz
Last active June 25, 2020 08:18
Show Gist options
  • Save szy0syz/89737ea72e98df317e65b318e5d57874 to your computer and use it in GitHub Desktop.
Save szy0syz/89737ea72e98df317e65b318e5d57874 to your computer and use it in GitHub Desktop.
我的阶段性小代码

The beautiful code

2020-05-24

  • from ERP system ---- "Altria-Serv"
positions
  .map((p) => p.parent)
  .forEach((org) =>
    data.filter((d) => d._id.toString() === org.toString()).forEach((i) => (i.isLeaf = false))
  );

2020-06-09

  • from ERP system ---- "Altria-Serv"
MenuSchema.static('populateTree', async function () {
  const nodes = await this.find({
    $or: [{ parent: null }, { parent: { $exists: false } }]
  });

  for (const node of nodes) {
    node.children = await node.populateTree();
  }

  return nodes;
});

MenuSchema.methods.populateTree = function () {
  const node = this;
  if (!node) return [];
  return this.constructor
    .find({ parent: this._id })
    .exec()
    .then(function (arrayOfChildren) {
      return Promise.each(arrayOfChildren, function (child) {
        if (Array.isArray(node.children)) {
          node.children.push(child);
        } else {
          node.children = [child];
        }
        child.parent = null;
        return child.populateTree();
      });
    });
};

2020-06-12

/**
 * 处理树形节点为指定格式
 * @param {Array<Object>} nodes 树形节点数组
 * @param {Function} func 转换函数
 */
const handleTreeNodes = (nodes, func) =>
  nodes.reduce((acc, cur) => {
    if (Array.isArray(cur.children) && cur.children.length > 0) {
      cur.children = handleTreeNodes(cur.children);
    }
    if (func && typeof func === 'function') {
      acc.push(func(cur));
    } else {
      acc.push(transformFunc(cur));
    }
    return acc;
  }, []);

2020-06-25

mongoose & async iterator

const { RepairIssue } = this.ctx.model;
const allIssues = RepairIssue
  .find({})
  .populate({ path: 'elevator', select: 'controlUnit adminOrgUnit' });

for await (const issues of allIssues) {
  const { elevator, adminOrgUnit, controlUnit } = issues;
  if (!adminOrgUnit.equals(elevator.adminOrgUnit)) {
    issues.adminOrgUnit = elevator.adminOrgUnit;
    issues.save();
  }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment