簡體   English   中英

javascript中的嵌套MongoDB查詢

[英]Nested MongoDB query in javascript

這是一個 GraphQL 解析器。 問題在於使用 async/await 處理 promise。

我曾嘗試實現承諾處理,但我無法以正確的方式進行設置,我在承諾處理方面沒有太多經驗,一些學習材料會很有幫助。

我的理解是腳本將在調用 await 的地方停止,並在 await 調用完成后繼續。 但它繞過了等待。 返回值后等待調用完成

    allDocs: async (args, context) => context().then(async client => {
        let db = client.db(dbName)
        const id = args.identifier.trim()
        let nameArr = []
        return await db.collection("collection").find({
            $or: [{
                "a.iden": id
            }, {
                "b.iden": id
            }]
        }).toArray().then(async (arr) => {
            let year
            arr.map(async element => {
                let pmcid = element.pmc_id.toUpperCase()      
                try {
                    year = await db.collection("Another_collection").findOne({"pmcid" : query})["year"]
                } catch (e) {
                    year = null
                }
                element["publication_year"] = year
            })
            return await arr
        }).then((arr)=>{
            client.close()
            return {
                "documents":  arr,
                "count": arr.length,
                "searchkey": id
            }
        })
    }),

預期的返回值應該有“publication_year”作為某個年份,它現在給出 null。

感謝幫助

您似乎將 Promise 與async/await混合使用,這有點難以理解。 最好通過更改 Promise 位以使用async/await來分解您的代碼,因為這將幫助您縮小問題的范圍。 您也可以將整個塊包裝在try/catch 中,這使得處理同步和異步錯誤相對容易。

因此,首先,您可以更改上下文函數調用,該調用返回使用 async await 作為的承諾

allDocs: async (args, context) => {
    try {
        const client = await context()

        ....
    } catch(err) {

    }
}

然后對toArray()函數調用做同樣的事情,它返回一個可以用async/await解析的承諾:

allDocs: async (args, context) => {
    try {
        const client = await context()
        const db = client.db(dbName)
        const id = args.identifier.trim()
        const results = await db.collection('collection').find({
            '$or': [
                { 'a.iden': id }, 
                { 'b.iden': id }
            ]
        }).toArray()

        const arr = results.map(async doc => {
            const pmcid = doc.pmc_id.toUpperCase()
            const { year } = await db.collection('Another_collection')
                                     .findOne({'pmcid' : pmcid })

            return {
                ...doc,
                publication_year: year
            }
        })

        client.close()

        return {
            'documents':  arr,
            'count': arr.length,
            'searchkey': id
        }
    } catch(err) {
        // handle error
    }
}

可以在單個調用中使用$lookup管道而不是在 map 循環中調用另一個集合以獲取publication_year 考慮以下管道

allDocs: async (args, context) => {
    try {
        const client = await context()
        const db = client.db(dbName)
        const id = args.identifier.trim()
        const pipeline = [
            { '$match': {
                '$or': [
                    { 'a.iden': id }, 
                    { 'b.iden': id }
                ]
            } },
            { '$lookup': {
                'from': 'Another_collection',
                'let': { 'pmcId': '$pmc_id' },
                'pipeline': [
                    { '$match': { 
                        '$expr': { 
                            '$eq': [
                                '$pmcid', 
                                { '$toUpper': '$$pmcId' }
                            ] 
                        }
                    } }
                ],
                'as': 'pmc'
            } },
            { '$addFields': {
                'publication_year': { 
                    '$arrayElemAt': [ '$pmc.year', 0 ]
                }
            } },
            { '$project': { 'pmc': 0 } }
        ]
        const arr = await db.collection('collection').aggregate(pipeline).toArray()

        client.close()

        return {
            'documents':  arr,
            'count': arr.length,
            'searchkey': id
        }
    } catch(err) {
        // handle error
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM