How do I query in MongoDB with Cloudflare workers?
Asked Answered
B

1

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

Bamboo answered 5/10, 2019 at 14:3 Comment(0)
T
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.)

Tyratyrannical answered 7/10, 2019 at 17:36 Comment(5)
BTW there are some great MongoDB HTTP interfaces available - See the following link for a comprehensive list docs.mongodb.com/ecosystem/tools/http-interfacesArchipelago
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.Bamboo
@Archipelago I checked interfaces and will need to check if they are available on serverless. I am currently experimenting with serverless technologies.Bamboo
@ 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.Archipelago
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 github.com/ysugimoto/cloudflare-worker-lambda-gatewayBamboo

© 2022 - 2024 — McMap. All rights reserved.