A lightweight utility library to simplify connecting and working with Amazon DocumentDB (with MongoDB compatibility).
Built for real-world usage, including production DocumentDB clusters, containerized local MongoDB, and Koa middleware integration.
- Features
- Installation
- Environment Variables
- Usage
- Koa Middleware
- Transactions
- API
- Local Development
- Troubleshooting
- Contributing
- Maintainers
- License
- Connect easily to DocumentDB or local MongoDB
- SSL/TLS support with AWS CA certificates
- Works with Docker-based Mongo
- Koa middleware support β
ctx.db - Supports transactions
- TypeScript friendly
- Minimal, simple API
npm install @awsmag/power-document-db| Variable | Description | Optional |
|---|---|---|
CONNECTION_URI |
Mongo/DocumentDB connection string | β |
DB_NAME |
Database name | β |
If set β
connectDb()can be called without arguments Otherwise β pass parameters explicitly
import { connectDb } from "@awsmag/power-document-db";
async function main() {
const db = await connectDb();
const users = await db.collection("users").find({}).toArray();
console.log(users);
}
main();import { connectDb } from "@awsmag/power-document-db";
async function main() {
const uri = "mongodb://localhost:27017";
const dbName = "test";
const ssl = false;
const tlsCAFile = "./certs/global-bundle.pem"; // Required only when ssl=true
const db = await connectDb(uri, dbName, ssl, tlsCAFile);
}Attach DB client automatically to ctx.db:
import Koa from "koa";
import { connectDb, getDbClientMw } from "@awsmag/power-document-db";
const app = new Koa();
(async () => {
await connectDb("mongodb://localhost:27017", "test");
app.use(getDbClientMw());
app.use(async ctx => {
const users = await ctx.db.collection("users").find({}).toArray();
ctx.body = users;
});
app.listen(3000);
})();import { startSession } from "@awsmag/power-document-db";
async function runWithTransaction(db) {
const session = await startSession();
try {
await session.startTransaction();
await db.collection("orders").insertOne({ item: "Book" }, { session });
await session.commitTransaction();
} catch (err) {
await session.abortTransaction();
console.error("Transaction aborted:", err);
} finally {
session.endSession();
}
}Returns: Promise<Db>
If no args β uses env variables
Returns: Promise<ClientSession>
Koa middleware β adds ctx.db
docker run \
-p 27017:27017 \
--name mongo \
mongo:latestThen connect using:
mongodb://localhost:27017
Use
ssl=falsefor local development.
| Issue | Fix |
|---|---|
| SSL enabled without CA bundle | Provide tlsCAFile |
| Timeout connecting to AWS DocDB | Check VPC + security group access |
| Transaction errors | Ensure cluster supports transactions |
ctx.db undefined |
Make sure connectDb() runs before middleware |
- Fork the repo
- Create branch β
feature/my-change - Add tests if needed
- Submit a PR