Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 669
Vishvendra Singh Avatar asked Oct 05 '19 14:10

Vishvendra Singh


People also ask

What database does Cloudflare use?

Meet D1, the database designed for Cloudflare Workers D1 is built on SQLite. Not only is SQLite the most ubiquitous database in the world, used by billions of devices a day, it's also the first ever serverless database.

Where do Cloudflare workers run?

One of the key differences between using Cloudflare Workers and using service workers is that service workers are run client-side and have to be downloaded by the user's browser, whereas Cloudflare Workers run in the edge of the Cloudflare network in between the user and the rest of the Internet, effectively running ...

Does Cloudflare have a database?

Content delivery network (CDN) and infrastructure Cloudflare, has launched a serverless database running on its Workers API. D1 is intended to provide instant database services for developers, without requiring them to install a full database.


1 Answers

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

like image 60
Kenton Varda Avatar answered Oct 15 '22 21:10

Kenton Varda