如何使用 Cloudflare worker 在 MongoDB 中进行查询?



我正在尝试查询mongodb简单的findOne在使用mongodb。Cloudflare 工作线程提供 10 毫秒的 CPU 时间,但在预览/发布抛出错误期间

我试过安装这些 npm 模块

npm i mongodb, mongodb-core, dgram, fs
var MongoClient = require('mongodb').MongoClient;
try{
var db = await MongoClient.connect('mongodb+srv://mongoURL',{ useNewUrlParser: true,useUnifiedTopology: true });
var dbo = db.db("test");
var result = await dbo.collection("testcollection").findOne()
const init = {
status: 200,
headers: { "Access-Control-Allow-Origin": "*", 'content-type': 'application/json' },
}
return new Response(JSON.stringify(result), init)
} catch(e) { console.log(e); return new Response(JSON.stringify(result), init)  }

抛出的错误在这里 - https://pastebin.com/xMKKjdZF

目前,Cloudflare Workers不支持原始TCP/UDP,仅支持HTTP/HTTPS。因此,您只能连接到提供 HTTP(S( 接口的数据库。MongoDB的协议不是基于HTTP的,所以你需要找到某种可以放在它前面的HTTP API代理。(另请注意,Cloudflare Workers不是基于Node.js,因此通常使用Node系统API的Node模块将不起作用。

最新更新