【问题标题】:Working with Koa,js and MongoDb使用 Koa、js 和 MongoDb
【发布时间】:2018-05-29 19:48:01
【问题描述】:

我有问题或什至没有问题只是对此知识不够,所以问题很简单,我有代码

router.get('/', (ctx, next) => {
    MongoClient.connect(url, {useNewUrlParser: true}, function (err, db) {
    if (err) throw err;
        let dbo = db.db("mydb");
        let query = {address: "Highway 37"};
        dbo.collection("customers").find(query).toArray((err, result) => {
            if (err) throw err;
            console.log(result)
            db.close();
        });
    });
    ctx.body = 'END OF FILE!!!';
});

console.log(result) 我有我的数据,我需要在 ctx.body 中响应这些数据,但我不知道如何将结果发送到我的 ctx.body,我正在尝试一些选项,例如创建变量和比如 let a 和 a = result 等等,但是所有的希望都没有了 :)

任何帮助将不胜感激,tnx 很多 ^)

【问题讨论】:

    标签: javascript node.js mongodb koa


    【解决方案1】:

    您的处理程序可能如下所示:

    router.get('/', ctx => {
      MongoClient.connect(..., (err, db) => {
        ...
        dbo.collection("customers").find(query).toArray((err, result) => {
          ctx.body = JSON.stringify(result)
        })
      })
    })
    

    【讨论】:

    • 问题是我不能从这个地方返回任何东西 dbo.collection("customers").find(query).toArray((err, result) => { "this place" ctx.body = "一些文本";
    • 为什么不呢?在获得数据之前,您无法将正文发回。
    • 如果我这样做 - dbo.collection("customers").find(query).toArray((err, result) => { ctx.body = "Text inside dbo collection" }) ;我没有在浏览器 console.log(ctx.body) 中找到而不是结果 - 返回未定义
    猜你喜欢
    • 2018-09-22
    • 1970-01-01
    • 2015-10-08
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 2017-10-05
    • 2012-05-28
    • 1970-01-01
    相关资源
    最近更新 更多