gpt4 book ai didi

javascript - 返回匹配字段数组的文档

转载 作者:行者123 更新时间:2023-11-28 00:20:47 25 4
gpt4 key购买 nike

将 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);
});

此返回(通过 express )

[{"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"]}]

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

最佳答案

总体思路是首先尝试使用 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);
});
});

关于javascript - 返回匹配字段数组的文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30050560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com