mongodbwebpack-2cloudflare-workerscloudflare-apps

How do I query in MongoDB with Cloudflare workers?


I am trying to query mongodb simple findOne in using mongodb. Cloudflare worker is giving 10ms CPU time but during preview/publish throwing error

I have tried installing these npm modules

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)  }

Error thrown is here - https://pastebin.com/xMKKjdZF


Solution

  • Currently, Cloudflare Workers does not support raw TCP/UDP, only HTTP/HTTPS. Hence you can only connect to databases that offer HTTP(S) interfaces. MongoDB's protocol is not HTTP-based, so you'll need to find some sort of HTTP API proxy you can put in front of it. (Also note that Cloudflare Workers is not based on Node.js, so in general Node modules that use Node's system APIs will not work.)