@apostrophecms/db-connect

中文文档
1.1.0发布于 2026/10/01MITCommonJS近 30 天下载 7202

Database connection library and dump/restore tools for ApostropheCMS

原始使用文档
文档目录8 节
  1. Supported Connection URLs
  2. MongoDB
  3. PostgreSQL
  4. SQLite
  5. Multi-Schema PostgreSQL (multipostgres)
  6. Connecting
  7. Atomicity
  8. API Reference

@apostrophecms/db-connect

@apostrophecms/db-connect defines the database connection API for ApostropheCMS. It provides adapters for MongoDB, PostgreSQL, and SQLite, and includes the apos-db-dump and apos-db-restore command-line utilities for database migration and backup.

The db-connect API is compatible with a large subset of the MongoDB API. However, after this introductory note, this document describes the db-connect API on its own terms. For projects that need to work across all three databases, it is necessary to use only the functionality defined here.

Supported Connection URLs

MongoDB

mongodb://localhost:27017/mydb
mongodb+srv://user:[email protected]/mydb

Standard MongoDB connection strings. The MongoDB adapter is a thin wrapper around the existing driver.

PostgreSQL

postgres://localhost:5432/mydb

Single-database mode. All collections are stored as tables in the public schema.

SQLite

sqlite:///path/to/database.db

File-based SQLite databases using better-sqlite3. The parent directory is created if it does not exist.

Unlike the others, this is not really a URL: everything after sqlite:// is a filesystem path, taken exactly as written. That matters, because filesystem paths are not URLs — they are not percent-encoded, they may contain characters a URL parser treats as significant, and on Windows they begin with a drive letter that a URL parser reads as host:port. So do not percent-encode the path. A space is a space:

sqlite:///Users/jane/My Project/data/site.db

%20 here means a literal percent, two, zero — not a space. Both absolute and relative paths work, and on Windows both separators do:

sqlite:///var/lib/mysite/data.db          absolute (POSIX)
sqlite://data/site.db                     relative to the working directory
sqlite://C:\Users\jane\site\data\site.db  absolute (Windows)
sqlite://C:/Users/jane/site/data/site.db  absolute (Windows, forward slashes)
sqlite:///C:/Users/jane/site/data/site.db absolute (Windows, file:// spelling)

In-memory databases (sqlite://:memory:) are not supported — the adapter assumes a persistent store suitable for hosting an ApostropheCMS site.

Multi-Schema PostgreSQL (multipostgres)

multipostgres://localhost:5432/shareddb-tenant1

Designed for use with the ApostropheCMS multisite module. In this mode, each site gets its own PostgreSQL schema within a single physical database.

The URL path is split at the last hyphen:

  • Everything before the last hyphen is the real PostgreSQL database name (shareddb)
  • Everything after is the schema name (tenant1)

Each schema is created automatically on first use and dropped cleanly when the database is dropped. This provides true multi-tenant isolation — no cross-tenant data leakage — while sharing a single PostgreSQL instance efficiently.

Connecting

const connect = require('@apostrophecms/db-connect');

const client = await connect('postgres://localhost:5432/mydb');
const db = client.db();
const articles = db.collection('articles');

// Insert a document
const result = await articles.insertOne({ title: 'Hello', status: 'draft' });

// Query documents
const docs = await articles.find({ status: 'draft' })
  .sort({ title: 1 })
  .limit(10)
  .toArray();

// Update a document
await articles.updateOne(
  { _id: result.insertedId },
  { $set: { status: 'published' } }
);

await client.close();

connect(uri) returns a client. Call client.db() to get a database, then db.collection(name) to get a collection.

Atomicity

insertOne and deleteOne are always atomic.

updateOne without upsert is atomic when it uses only the following operators:

  • $set, $inc, $unset, $currentDate — always atomic
  • $push, $pull, $addToSet — atomic when all values are scalars (strings, numbers, booleans). Object or array values fall back to read-modify-write.

These operators can be freely combined in a single updateOne call and the entire update will be atomic. This covers the most common patterns: counters, status flags, timestamps, field cleanup, and adding/removing items to/from arrays.

The following operations are NOT guaranteed to be atomic and use a read-modify-write pattern (the document is read, the update is applied in JavaScript, and the result is written back):

  • updateOne with $rename or upsert: true
  • updateOne with $push, $pull, or $addToSet using non-scalar values
  • updateMany, findOneAndUpdate, and replaceOne

For operations that must be atomic and aren't covered above, use advisory locking (apos.lock) to serialize access. Apostrophe core already uses advisory locking where atomicity matters (e.g., apos.lock.lock around critical sections).

API Reference

  • Database and Client — client.db(name), listing collections, dropping databases
  • Collection Methods — CRUD operations, cursors, and bulk writes
  • Query Operators — filtering documents with comparison, logical, element, and array operators
  • Update Operators — modifying documents with $set, $inc, $push, and more
  • Indexes — creating and managing indexes, including numeric and date types
  • Aggregation — pipeline stages and group accumulators
  • Dump and Restore — CLI tools and programmatic API for backup and migration

版本与发布记录

@apostrophecms/db-connect 共发布 7 个版本,首次发布于 2026/04/21;过去 12 个月发布了 7 个版本。

版本发布日期距今
1.1.0latest2026/10/011 个月前
1.0.22026/09/032 个月前
1.0.2-alpha.0alpha2026/09/032 个月前
1.0.12026/06/104 个月前
1.0.0-alpha.22026/06/104 个月前
1.0.02026/06/055 个月前

关于 @apostrophecms/db-connect 的常见问题

@apostrophecms/db-connect 是什么?

Database connection library and dump/restore tools for ApostropheCMS

如何安装 @apostrophecms/db-connect?

在项目目录运行 npm install @apostrophecms/db-connect,或使用 pnpm add / yarn add / bun add。它还提供命令行工具 apos-db-dump、apos-db-restore,可以用 npx apos-db-dump 直接运行。

@apostrophecms/db-connect 支持 TypeScript 吗?

该包的 package.json 没有声明类型入口。需要类型提示时,可以在 npm 上查找社区维护的 @types/apostrophecms__db-connect 是否存在。

@apostrophecms/db-connect 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@apostrophecms/db-connect 可以商用吗?

@apostrophecms/db-connect 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@apostrophecms/db-connect 的下载量有多少?

根据 npm 官方下载统计,@apostrophecms/db-connect 在 2026/10/07 – 2026/11/05 这 30 天内被下载 7,202 次,日均约 240 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@apostrophecms/db-connect 还在维护吗?

最新版本 1.1.0 发布于 2026/10/01(1 个月前);至今共发布 7 个版本,其中过去 12 个月发布了 7 个;首次发布于 2026/04/21。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。