7

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

Vishvendra Singh
  • 484
  • 5
  • 19

1 Answers1

10

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

Kenton Varda
  • 41,353
  • 8
  • 121
  • 105
  • BTW there are some great MongoDB HTTP interfaces available - See the following link for a comprehensive list https://docs.mongodb.com/ecosystem/tools/http-interfaces/ – JWPersh Oct 12 '19 at 18:24
  • yes @Kenton I checked CF worker docs and found none on TCP connections. So Tried invoking aws lambda but webpack is throwing error for aws-sdk. Finally achieved this with mongo-stitch. – Vishvendra Singh Oct 12 '19 at 22:50
  • 1
    @JWPersh I checked interfaces and will need to check if they are available on serverless. I am currently experimenting with serverless technologies. – Vishvendra Singh Oct 12 '19 at 22:53
  • @ Vishvendra Singh If you are hosting your own MongoDB instance then you can use the interfaces on your server that is running MongoDB to allow HTTP calls. You can then make HTTP calls in a Cloudflare worker to that HTTP mongo interface. – JWPersh Oct 12 '19 at 23:42
  • Interfaces are awesome and ideal choice @JWPersh, completely solves my problem. Unfortunately, I am using mongoDB cloud. While searching I found this repo that can invoke lambda from worker https://github.com/ysugimoto/cloudflare-worker-lambda-gateway – Vishvendra Singh Nov 05 '19 at 06:44