获取节点js

时间:2021-03-04 10:17:16

标签: node.js arrays mongodb

嗨,我在 mongo db 中有 2 个集合,我需要根据另一个集合的某些条件从一个集合中检索一些结果。

我根据某些条件从我的第一个集合中获取 _id 字段,并且我得到了一组对象 _id。我正在循环这个数组并尝试从与这个 _id 匹配的第二个集合中获取结果。

第二个数组的结果是另一个对象数组。如下图,

[
 {
  portfolio: [
   [Object], [Object],
   [Object], [Object],
   [Object], [Object],
   [Object], [Object]
 ],
 _id: 603e0129e879ce0954caf7b9
 }
]
[
 {
 portfolio: [
   [Object], [Object],
   [Object], [Object],
   [Object], [Object],
   [Object], [Object]
 ],
_id: 603e0147e879ce0954caf7ba
 }
 ]

我需要将这些投资组合数组推送到另一个空数组。下面是我使用的代码。

public async bestCall() {
    let currentdate = this.checkTime();
    currentdate = currentdate.substring(0, currentdate.indexOf(' '));
    let updateData: Array<String> = []; //this is the array to which I need to push my result elements
    var records = await this.sc.find({ conDate: { $lte: currentdate }, conEnd: { $gte: new Date(currentdate) }, conTypeId: 2 }, { _id: 1 });
    records.forEach(async (element) => {
        let result: any = await this.pf.find({ stContestId: element._id }, { portfolio: 1 });
        for (let i = 0; i < result.length; i++) {
            await (result[i]['portfolio'].ticker).map(async (value: any) => {
                updateData.push(value)
            })
        }
    });
    console.log(updateData) //this is empty
}

投资组合是一组对象:

 "portfolio":[
   {"sn":{"numberInt":"0"},
   "sector":"Communication",
   "ticker":"TEST",
   "logo":"https://xxx",
   "x":{"numberInt":"0"},
   "i":{"numberInt":"0"},
   "p":{"numberInt":"0"},
   "cp":{"numberInt":"0"},
   "cpp":{"numberInt":"0"},
   "ind":{"numberInt":"0"}} ]

我使用以下代码通过 mongo db 查找进行了尝试,但失败了。结果只给了我 inout 集合的数据,而不是第二个集合的投资组合:

var res: any = await this.sc.aggregate([
        {
            "$match": {
                $and: [{ "conDate": { $lte: currentdate }, conEnd: { $gte: new Date(currentdate) }, "conTypeId": { $eq: 2 } }

                ]
            }
        },
        {
            $lookup: {
                from: "pf",
                localField: "_id",
                foreignField: "stContestId",
                as: "portfolio"
            }
        },
        {
            "$project": {
                "portfolio": 1
            }
        }

    ]);
    for (let i = 0; i < res.length; i++) {
        console.log(res.length)
        console.log(res[i])
    }
}

Result 在循环内推送到 updateData 数组,但没有在 foreach 循环之外获取它。我怎样才能让它脱离循环

0 个答案:

没有答案