@spica-devkit/database
Get a native MongoDB connection inside Spica functions for advanced queries, and understand why the APIs are usually the better choice.
@spica-devkit/database gives functions a native MongoDB driver connection to Spica's database. It only works inside Spica functions on MongoDB instances.
npm install @spica-devkit/databaseimport {database, ObjectId} from "@spica-devkit/database";
export default async function () {
const db = await database();
const posts = db.collection(`bucket_${process.env.POSTS_BUCKET_ID}`);
return posts
.aggregate([
{$match: {status: "published"}},
{$group: {_id: "$author", count: {$sum: 1}}},
{$sort: {count: -1}},
{$limit: 5}
])
.toArray();
}| Export | Description |
|---|---|
database() | Connects (once per worker) and returns the MongoDB Db. |
ObjectId | MongoDB's ObjectId class. |
close(force?) | Close the connection. Called for you when the worker stops. |
isConnected() | Whether a connection is open. |
Bucket documents live in collections named bucket_<bucketId>.
Before you use it
Writing to the database directly skips everything the API does:
- No schema validation, defaults or rules.
- No history, activity records or response cache invalidation.
- Hashed and encrypted properties are stored in their protected form.
- The internal data layout can change between releases.
For that reason the package prints a FootgunWarning on first use. Prefer @spica-devkit/bucket with an API key, and reserve direct access for read-only analytics such as aggregations. Set the NO_DEVKIT_DATABASE_WARNING environment variable on the function to silence the warning once you have made that choice.
--experimental-function-devkit-database-cache makes repeated connections faster.