Query Data from MongoDB
In this example, we’re going to build an Endpoint that allows us to read data from a Database. We’ll be using MongoDB in this example, but you can easily swap this out with PostgreSQL or MySQL!
Before we get started with building the Endpoint, let’s create the needed Environment Variables. Head over to the “Environment Variables” section in the Sidebar, located on the right-hand side of the app and create the following variable:
- 1.
MONGODB_URI
- Your MongoDB connection string
To enable Buildable to connect to your database, please ensure that your firewall accepts incoming requests from the following IP address:
35.245.232.82

If you’ve got a separate database for Development and Production, ensure to specify the appropriate values when creating the Environment Variable.
- 1.Create an Endpoint named
query-mongodb-data
and set the method type toPOST

2. Paste the following code into the
Code
sectionasync function response({ body, headers, env }) {
const { collection, query, limit, skip } = body;
const data = await find(env.MONGODB_URI, collection, query, limit, skip);
return {
status: 200, // HTTP Response Status Code
headers: {}, // Response Headers
// Response Body
body: data
}
}
async function find(uri, collection, query, limit, skip) {
const db = new MongoDBHelper(uri)
return await db.find(collection, query, limit, skip)
}
class MongoDBHelper {
constructor(uri) {
this.uri = uri
}
async connect() {
const MongoClient = require("mongodb").MongoClient
const client = new MongoClient(this.uri)
await client.connect()
this.db = client.db()
this.client = client
}
async disconnect(client) {
await this.client.close()
}
async find(collectionName, query, limit = 1, skip = 0) {
await this.connect()
const collection = this.db.collection(collectionName)
const result = await collection
.find(query)
.limit(limit)
.skip(skip)
.toArray()
await this.disconnect()
return result
}
}
You can also select the
Query data from MongoDB
example from the Snippets section, located next to the Code editor.
Given a body payload that contains a collection, query, limit, and skip value, this Endpoint will query your Mongo Database and return the data! Give your Endpoint a try with this sample body payload:
{
"collection": "YOUR_COLLECTION_NAME",
"query": {},
"limit": 10,
"skip": 0
}
Using the Knex NPM package, you can query and interface with various databases such as PostgreSQL, MySQL, CockroachDB, MSSQL, SQLite3, Oracle, etc.
Last modified 5mo ago