返回匹配字段数组的文档

时间:2015-05-05 10:32:25

标签: javascript mongodb mongoose

将Mongoose与MongoDB一起使用,我需要根据初始查找字段返回一系列查找。我的架构如下:

var PartSchema = new Schema({
    partcode: String,
    children: [String]
});

数据如下所示:

[{"partcode":"A1","children":["B1","B2","B3","B4"]},
 {"partcode":"B1","children":["C11","C21","C31","C41"]},
 {"partcode":"B2","children":["C12","C22","C32","C42"]},
 {"partcode":"B3","children":["C13","C23","C33","C43"]},
 {"partcode":"B4","children":["C14","C24","C34","C44"]}]

我可以使用以下静态调用查询A1的子字段:

var childrenOnly =
  {children: 1, _id: 0};
PartSchema.static('getChildren', function (partcode, callback) {
  return this.find({ partcode: partcode }, childrenOnly, callback);
});

返回(通过快递)

[{"children":["B1","B2","B3","B4"]}]

我需要它返回的是

[{"partcode":"B1","children":["C11","C21","C31","C41"]},
 {"partcode":"B2","children":["C12","C22","C32","C42"]},
 {"partcode":"B3","children":["C13","C23","C33","C43"]},
 {"partcode":"B4","children":["C14","C24","C34","C44"]}]

我猜测第一个查询返回children数组时需要进行迭代调用,然后迭代子数组以获取每个子记录。

1 个答案:

答案 0 :(得分:1)

一般的想法是首先使用 findOne() 方法尝试使用子代码获取数组,然后使用该数组作为$in运算符的查询 find() 方法返回完整结果。

var childrenOnly = {children: 1, _id: 0};
PartSchema.static('getChildren', function (partcode, callback) {
    var self = this;
    this.findOne({ partcode: partcode }, childrenOnly)
        .exec(function (err, doc) {
             console.log(doc.children); // {"children":["B1","B2","B3","B4"]}
             return self.find({"partcode": {"$in": doc.children} }, callback);
        });
});

- 编辑 -

使用 promises 查看。我还没有对此进行测试,但我相信它也应该做到这一点:

var childrenOnly = {children: 1, _id: 0};
PartSchema.static('getChildren', function (partcode, callback) {
    var self = this,
        promise = this.findOne({ partcode: partcode }, childrenOnly).exec();
    promise.then(function (doc) {
        return self.find({"partcode": {"$in": doc.children} }, callback);            
    });               
});