繁体   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