Mongoose:在数组中查找标签并返回匹配的文档

Ter*_*rry 6 mongoose mongodb

在我目前的Mongo DB中,我有一个简单的Parts集合,具有Parent Children关系,如下所示:

{"partcode": "Parent1","children": ["Child1","Child2","Child3"]}

{"partcode": "Child1","label": ["label1"]}
{"partcode": "Child2","label": ["label1"]}
{"partcode": "Child3","label": ["label1"]}
Run Code Online (Sandbox Code Playgroud)

为了返回partcode的子代,我使用以下Mongoose函数:

PartSchema.static('getChildren', function(query, callback) {
  var self = this,
  self.findOne(query, {children: 1, _id: 0})
    .exec(function(err, doc) {
      return (self.find({
        "partcode": {
          "$in": doc.children
        }
      }, {_id: 0}, callback));
    });
});
Run Code Online (Sandbox Code Playgroud)

这将返回以下数组:

[{"partcode": "Child1","label": ["label1"]},
{"partcode": "Child2","label": ["label1"]},
{"partcode": "Child3","label": ["label1"]}]
Run Code Online (Sandbox Code Playgroud)

我想实现一个标签系统,我可以将标签指定为元子,并使代码返回与该标签匹配的所有子标签.

{"partcode": "Parent1","children": ["*label1"]}
Run Code Online (Sandbox Code Playgroud)

会回来:

[{"partcode": "Child1","label": ["label1"]},
{"partcode": "Child2","label": ["label1"]},
{"partcode": "Child3","label": ["label1"]}]
Run Code Online (Sandbox Code Playgroud)

我将在父文档的子字段中指定一个标签,以特殊字符开头(目前,我正在使用'*',但如果需要,我很乐意将其更改为其他内容).

伪代码:

  1. 父母
  2. 获取Parent数组
  3. 在数组中,如果子项标签字符 开头
    1. 获取匹配label和的所有部件代码的数组
    2. 替代partcodes的标签在儿童阵列
  4. 返回数组

不应以标签字符开头的儿童也应退回.

Ter*_*rry 1

我让它按如下方式工作:

PartSchema.static('getChildren', function(query, callback) {
  var self = this,
    children = [],
    labels = [];
  self.findOne(query, {children: 1, _id: 0})
    .exec(function(err, doc) {
      //find labels
      labels = _.filter(doc.children, obj => /^\*/.test(obj));
      //remove labels from children array
      children = _.difference(doc.children, labels);
      //remove label identifier '*'
      labels = _.map(labels, label => label.substring(1));
      self.find({
        vendor: vendor,
        $or: [{
          "partcode": {
            "$in": children
          }
        }, {
          "label": {
            "$in": labels
          }
        }]
      }, {_id: 0}, callback);
    });
});
Run Code Online (Sandbox Code Playgroud)

我对评论感兴趣。特别是在优雅、结构、惯例等方面。有什么形式如此糟糕或丑陋的东西会让你眼花缭乱吗?