【问题标题】:How to fix node.js returning {} when using async with mongoDB如何在将异步与 mongoDB 一起使用时修复 node.js 返回 {}
【发布时间】:2019-04-29 05:30:24
【问题描述】:

我试图让 node.js 在调用时从 mongoDB 数据库返回信息。在我的数据库中,我有

_id: ObjectID("5cc0fe18f7875c00bc88de4c")
url:"google.com?ref_source=test"
count:0

基本上,当我执行http://localhost:8080/count/google.com+test 时,我希望我的代码进入 MongoDB 并检索count 前面的值。当我运行此代码时,结果 1 被记录但没有返回。而是返回 {}

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
app.use(bodyParser.text())
var MongoClient = require('mongodb').MongoClient;
var mongourl = "mongodb://localhost:27017/";

async function getcount(fullurl) {


    try{
        var db = await MongoClient.connect(mongourl) //Connect to mongoDB
        var dbo = db.db("analytics")  //Connect to analytics DB
        var query = {url: fullurl}  //Find results with the input under URL
        var result = await dbo.collection("main").find(query).toArray()  //Connect to main collection
        let res = JSON.stringify(result)
        res = res.substring(res.indexOf(":") + 1)
        res = res.substring(res.indexOf(":") + 1)
        res = res.substring(res.indexOf(",") + 1)
        res = res.substring(res.indexOf('":') + 2)
        res = res.substring(0, res.indexOf('}]'))
        // Get result
        db.close()
        return await res  //Return it
    }
    catch(error)
    {
        return error
    }


}

function isURL(str){
    var pattern = new RegExp('^((ft|htt)ps?:\\/\\/)?'+ // protocol
        '((([a-z\\d]([a-z\\d-]*[a-z\\d])*)\\.)+[a-z]{2,}|'+ // domain name and extension
        '((\\d{1,3}\\.){3}\\d{1,3}))'+ // OR ip (v4) address
        '(\\:\\d+)?'+ // port
        '(\\/[-a-z\\d%@_.~+&:]*)*'+ // path
        '(\\?[;&a-z\\d%@_.,~+&:=-]*)?'+ // query string
        '(\\#[-a-z\\d_]*)?$','i'); // fragment locator
    return pattern.test(str);
}



async function count(string){
    try {
        //console.log(string)
        string = string.split("(!").join("/");
        //console.log(string)
        string = string.split("/?ref_source=").join("+");
        //console.log(string)
        string = string.split("https://").join("");
        //console.log(string)
        lengths = string.split("+")
        toReturn = ("Not a Valid Url Input: " + lengths[0])
        if (isURL(lengths[0])) {
            if ((lengths[1] == "") || (lengths[1] == "undefined")) {
                return "Not A Valid Identifier Input"
            }
            fullurl = (lengths[0] + "?ref_source=" + lengths[1])
            console.log(fullurl)
            let response = await(getcount(fullurl))
            console.log(response)  //Log the info
            return await (response) //Return it.  THIS is THE PART THAT FAILS
        }
    }
    catch(error)
    {
        return error
    }

}


app.get('/count/:string', (req, res) => {
    res.send((count(req.params.string)))
})
app.listen(8080, () => console.log('> Listening!'))

【问题讨论】:

    标签: node.js mongodb asynchronous


    【解决方案1】:

    由于 count 是一个异步函数,您必须在使用 res.send() 发送结果之前等待结果,类似这样(注意我在函数之前添加了异步。

    app.get('/count/:string', async (req, res) => {
        let result = await count(req.params.string)
        res.send(result)
    })
    

    或者你必须使用promise

    app.get('/count/:string', (req, res) => {
        count(req.params.string).then(result =>{
           res.send(result)
        })
    })
    

    【讨论】:

    • 完美运行,非常感谢!花了几天时间试图弄清楚这一点。
    【解决方案2】:

    当您“返回等待资源”时,您是在告诉 Node 您正在返回一个 Promise。您应该只使用“return res”(在 getcount 中)和“return response”(在您的 count 函数中),因为它们都是已经定义的变量,而不是实际的异步函数。

    【讨论】:

      猜你喜欢
      • 2021-01-02
      • 2019-10-21
      • 2016-09-16
      • 2013-07-20
      • 2020-06-21
      • 2018-04-16
      • 2013-09-11
      • 2019-11-10
      相关资源
      最近更新 更多