【问题标题】:Can't return JSON from Cosmos DB (MongoDB schema) using a NodeJS Azure Function无法使用 NodeJS Azure 函数从 Cosmos DB(MongoDB 架构)返回 JSON
【发布时间】:2020-07-23 10:11:38
【问题描述】:

我正在尝试使用 azure 函数从 cosmosdb(MongoDB 架构)中检索数据。我可以记录数据,但无法将其检索到客户端。它什么也没显示,当我尝试使用浏览器或邮递员调用该函数时。知道如何返回这个 mongodb 对象数组吗?

import { AzureFunction, Context, HttpRequest } from "@azure/functions";
import { MongoClient } from "mongodb";
import assert from "assert";

const url = "";


const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
    MongoClient.connect(url, async (err, db) => {
        let dbo = db.db("MyDB");
    
        var cursor = await dbo.collection("test").find({}).toArray((err, docs) => {

            if(err) {
                context.res = {
                    body: err,
                }
            }
            if (docs) {
                context.res.set('content-type', 'application/json')
                context.res = {
                    status: 200,
                    body: docs
                };

                console.log(context.res );
            }
            else {
                context.res = {
                    status: 400,
                    body: "No docs"
                };
            }

            context.res.headers = { 'Content-Type':'application/json' };

            context.done();

            console.log("DONE");
        });

        db.close();
      
      });


};

export default httpTrigger;

【问题讨论】:

  • 必须返回一个 Promise。

标签: node.js mongodb azure function serverless


【解决方案1】:

关于问题,请参考以下代码

import { AzureFunction, Context, HttpRequest } from "@azure/functions";
import { MongoClient } from "mongodb";

const url = "";


const httpTrigger: AzureFunction = async function (context: Context, req: HttpRequest): Promise<void> {
try {
    var client =await MongoClient.connect(url , {useNewUrlParser: true,useUnifiedTopology: true})
    const db=client.db("test");
    const cursor =db.collection('Users').find({'saying':'English'});
    const docs =await cursor.toArray();
   
    console.log("done")
    context.res={
        status: 200,
        body: docs,
        headers: {
            'Content-Type': 'application/json'
        }
       }
    
   } catch (error) {
       context.log(error);
       context.res={
        status: 500,
        body: error
       }
   }finally{

      await client.close();
      console.log("closed")
   }
    
    
    
};

export default httpTrigger;

【讨论】:

  • 谢谢,最后我用 Promise 做到了。
猜你喜欢
  • 1970-01-01
  • 2019-02-17
  • 1970-01-01
  • 1970-01-01
  • 2018-04-10
  • 1970-01-01
  • 2019-03-30
  • 2019-02-08
  • 1970-01-01
相关资源
最近更新 更多