蓝色天空.知识 · 实践 · 创造
我的收藏
Node.js 教程目录 38章
Node.js / LEARN BY DOING

Node.js MongoDB

核对 MongoDB 文档数据库接入流程、MongoClient URI 连接、集合 CRUD、投影筛选、排序分页、$lookup 聚合左连接、集合删除与 Promise 异步链的离线语义实测。

学完这一章,你能够

  • 核对 MongoDB 文档数据库接入流程、MongoClient URI 连接、集合 CRUD、投影筛选、排序分页、$lookup 聚合左连接、集合删除与 Promise 异步链的离线语义实测。

驱动接入、MongoClient 连接与库/集合创建

MongoDB 是由 C++ 编写的面向文档(BSON/JSON)数据库管理系统。在 Node.js 项目中可通过安装官方驱动 `mongodb`(参考命令如 `npm install mongodb` 或 `cnpm install mongodb`)获取 `MongoClient` 类来管理连接会话。连接字符串 `uri` 遵循 `mongodb://[username:password@]host1[:port1][,...hostN[:portN]][/[defaultauthdb][?options]]` 规范(本地默认 `mongodb://localhost:27017`),连接成功后应在 `finally` 中调用 `await client.close()` 回收句柄。补充说明:历史示例常见的 `useNewUrlParser` 与 `useUnifiedTopology` 在官方驱动 v4+ 已成默认行为并在新版本中移除,无需再显式传入。

通过 `client.db(dbName)` 指定数据库后,MongoDB 采用按需延迟建库机制——若数据库尚不存在,首次写入文档或显式调用 `database.createCollection(collectionName)` 时才会实际创建数据库与集合;也可直接用 `database.collection(name)` 获取集合句柄立即写入。

文档插入、条件查询、更新与删除操作

与关系型数据库需先建表不同,MongoDB 在向新集合写入时可自动创建集合并生成全局唯一 `_id`(默认 `ObjectId`)。单条写入调用 `insertOne(doc)` 返回 `insertedId`,批量写入调用 `insertMany(docs)` 返回 `insertedCount` 与 `insertedIds` 映射;在交互客户端 `mongosh` 中则可用 `show dbs`、`use <db>`、`show tables` 与 `db.<collection>.find()` 检视落盘文档。

查询文档使用 `collection.find(query, options)` 返回游标,再通过 `await cursor.toArray()` 取出结果数组:传入空对象 `{}` 查询全集,传入 `{ name: 'Alice' }` 按条件精确筛选,并在 `options.projection` 中控制返回字段(如 `{ _id: 0, name: 1, age: 1 }` 隐藏 `_id`)。本站 Node.js v24.22.3 本地契约实测解析 `mongodb://localhost:27017/appdb`(主机 `localhost`、端口 `27017`、库名 `appdb`),批量插入 3 条文档后全量投影返回 3 项且不含 `_id`,按 `{ name: 'Alice' }` 过滤精确命中 `Wonderland` 单条记录。

修改文档必须配合更新操作符(如 `$set`)指定变更字段:`updateOne(filter, { $set: ... })` 仅修改首条命中文档,`updateMany(filter, { $set: ... })` 更新全部匹配文档,两者均返回 `matchedCount` 与 `modifiedCount`。删除文档同理区分为 `deleteOne(filter)` 与 `deleteMany(filter)` 并返回 `deletedCount`。本站实测在 4 条文档上执行上述 4 项操作:`updateOne` 命中 `1` 条、`updateMany` 修改 `2` 条、`deleteOne` 删除 `1` 条、`deleteMany({ type: 'en' })` 删除 `2` 条,最终集合精确剩余 `["Bob"]`。

排序分页、$lookup 聚合左连接、删除集合与 Promise 异步链

游标支持链式排序与分页:`sort({ field: 1 })` 按升序排列、`sort({ field: -1 })` 按降序排列;`limit(n)` 限制最多返回条数,`skip(m)` 跳过前 `m` 条文档,两者组合即可实现分页切片。本站实测 5 条文档(年龄 25/30/35/20/22)按 `age` 升序得 `[20, 22, 25, 30, 35]`、降序得 `[35, 30, 25, 22, 20]`,`limit(3)` 返回前 3 名 `["Alice","Bob","Charlie"]`,`skip(2).limit(2)` 返回 `["Charlie","Dave"]`。

尽管 MongoDB 不是关系型数据库,仍可通过聚合管道操作符 `$lookup` 实现左外连接(left outer join):指定 `from`(目标集合)、`localField`(当前集合关联键)、`foreignField`(目标集合关联键)与 `as`(输出数组字段名),把关联文档嵌入每条主文档中;未命中任何关联项时目标数组为空。清理不再使用的集合则可调用 `collection.drop()`(成功返回 `true`)。本站实测将 `orders` 的 `product_id` 关联到 `products._id`,订单 1 准确挂接 `Product A`,而 `product_id=999` 的订单保留在结果中且 `productDetails` 长度为 `0`;随后 `drop()` 返回 `true`。

现代官方 `mongodb` Node.js 驱动(v4+)所有异步方法均原生返回 `Promise`,可直接配合 `async`/`await` 或 `.then()`/`.catch()` 串联“连接 → 插入 → 查询 → 更新 → 删除 → 关闭”完整链路,无需再像旧版驱动(v3)那样手工用 `new Promise` 包装回调,且构造 `ObjectId` 时应使用 `new ObjectId(id)`。本站实测一条完整 Promise/async CRUD 链:插入后计数为 `1`、更新后站点变为 `updated.example`、删除后查询结果归零为 `[]`。

运行离线文档存储 URI 解析、CRUD、排序分页、$lookup 左连接与 Promise 链实验

含完整源码 · 351 行
展开查看收起
javascript
function matchesFilter(doc, filter = {}) {
  return Object.entries(filter).every(([k, v]) => doc[k] === v);
}

function applyProjection(doc, projection) {
  if (!projection) return structuredClone(doc);
  const out = {};
  const includeKeys = Object.entries(projection).filter(([k, v]) => k !== '_id' && v === 1);
  if (includeKeys.length > 0) {
    if (projection._id !== 0 && '_id' in doc) out._id = doc._id;
    for (const [k] of includeKeys) {
      if (k in doc) out[k] = doc[k];
    }
    return out;
  }
  for (const [k, v] of Object.entries(doc)) {
    if (projection[k] !== 0) out[k] = v;
  }
  return out;
}

class LocalCursor {
  constructor(docs, projection) {
    this._docs = docs;
    this._projection = projection;
    this._sortSpec = null;
    this._skipCount = 0;
    this._limitCount = null;
  }
  sort(spec) {
    this._sortSpec = spec;
    return this;
  }
  skip(n) {
    this._skipCount = n;
    return this;
  }
  limit(n) {
    this._limitCount = n;
    return this;
  }
  async toArray() {
    let list = this._docs.map((d) => structuredClone(d));
    if (this._sortSpec) {
      const [[field, dir]] = Object.entries(this._sortSpec);
      list.sort((a, b) => (a[field] < b[field] ? -dir : a[field] > b[field] ? dir : 0));
    }
    if (this._skipCount > 0) list = list.slice(this._skipCount);
    if (this._limitCount !== null) list = list.slice(0, this._limitCount);
    return list.map((d) => applyProjection(d, this._projection));
  }
}

class LocalCollection {
  constructor(db, name) {
    this._db = db;
    this.name = name;
    this._docs = [];
    this._seq = 1;
  }
  async insertOne(doc) {
    const _id = doc._id ?? `oid_${this._seq++}`;
    this._docs.push({ _id, ...structuredClone(doc) });
    return { acknowledged: true, insertedId: _id };
  }
  async insertMany(docs) {
    const insertedIds = {};
    for (let i = 0; i < docs.length; i++) {
      const res = await this.insertOne(docs[i]);
      insertedIds[i] = res.insertedId;
    }
    return { acknowledged: true, insertedCount: docs.length, insertedIds };
  }
  find(filter = {}, options = {}) {
    const matched = this._docs.filter((d) => matchesFilter(d, filter));
    return new LocalCursor(matched, options.projection);
  }
  async findOne(filter = {}, options = {}) {
    const hit = this._docs.find((d) => matchesFilter(d, filter));
    return hit ? applyProjection(hit, options.projection) : null;
  }
  async updateOne(filter, update) {
    const hit = this._docs.find((d) => matchesFilter(d, filter));
    if (!hit) return { matchedCount: 0, modifiedCount: 0 };
    if (update.$set) Object.assign(hit, update.$set);
    return { matchedCount: 1, modifiedCount: 1 };
  }
  async updateMany(filter, update) {
    let matchedCount = 0;
    for (const d of this._docs) {
      if (matchesFilter(d, filter)) {
        matchedCount++;
        if (update.$set) Object.assign(d, update.$set);
      }
    }
    return { matchedCount, modifiedCount: matchedCount };
  }
  async deleteOne(filter) {
    const idx = this._docs.findIndex((d) => matchesFilter(d, filter));
    if (idx === -1) return { deletedCount: 0 };
    this._docs.splice(idx, 1);
    return { deletedCount: 1 };
  }
  async deleteMany(filter) {
    const before = this._docs.length;
    this._docs = this._docs.filter((d) => !matchesFilter(d, filter));
    return { deletedCount: before - this._docs.length };
  }
  aggregate(pipeline) {
    let current = this._docs.map((d) => structuredClone(d));
    for (const stage of pipeline) {
      if (stage.$lookup) {
        const { from, localField, foreignField, as } = stage.$lookup;
        const foreignDocs = this._db.collection(from)._docs;
        current = current.map((doc) => ({
          ...doc,
          [as]: foreignDocs
            .filter((f) => f[foreignField] === doc[localField])
            .map((f) => structuredClone(f)),
        }));
      }
    }
    return { toArray: async () => current };
  }
  async drop() {
    return this._db._collections.delete(this.name);
  }
}

class LocalDb {
  constructor(name) {
    this.databaseName = name;
    this._collections = new Map();
  }
  async createCollection(name) {
    if (!this._collections.has(name)) {
      this._collections.set(name, new LocalCollection(this, name));
    }
    return this._collections.get(name);
  }
  collection(name) {
    if (!this._collections.has(name)) {
      this._collections.set(name, new LocalCollection(this, name));
    }
    return this._collections.get(name);
  }
}

class LocalMongoClient {
  constructor(uri) {
    this.uri = uri;
    this.parsed = new URL(uri);
    this._dbs = new Map();
    this.connected = false;
  }
  async connect() {
    this.connected = true;
    return this;
  }
  db(name) {
    const dbName = name || this.parsed.pathname.replace(/^\/+/, '') || 'test';
    if (!this._dbs.has(dbName)) this._dbs.set(dbName, new LocalDb(dbName));
    return this._dbs.get(dbName);
  }
  async close() {
    this.connected = false;
  }
}

async function main() {
  const client = new LocalMongoClient('mongodb://localhost:27017/appdb');
  const cases = [];

  try {
    await client.connect();
    const db = client.db();

    // Case 1: uri_parse_and_insert_find_projection
    const col1 = await db.createCollection('exampleCollection');
    await col1.insertMany([
      { name: 'Alice', age: 25, address: 'Wonderland' },
      { name: 'Bob', age: 30, address: 'Builderland' },
      { name: 'Charlie', age: 35, address: 'Chocolate Factory' },
    ]);
    const allProj = await col1
      .find({}, { projection: { _id: 0, name: 1, age: 1 } })
      .toArray();
    const aliceOnly = await col1
      .find({ name: 'Alice' }, { projection: { _id: 0, name: 1, address: 1 } })
      .toArray();
    const actual1 = {
      host: client.parsed.hostname,
      port: Number(client.parsed.port),
      dbName: db.databaseName,
      totalCount: allProj.length,
      hasIdField: '_id' in allProj[0],
      aliceMatch: aliceOnly,
    };
    const expected1 = {
      host: 'localhost',
      port: 27017,
      dbName: 'appdb',
      totalCount: 3,
      hasIdField: false,
      aliceMatch: [{ name: 'Alice', address: 'Wonderland' }],
    };
    cases.push({
      name: 'uri_parse_and_insert_find_projection',
      passed: JSON.stringify(actual1) === JSON.stringify(expected1),
      expected: expected1,
      actual: actual1,
    });

    // Case 2: update_and_delete_one_many
    const col2 = await db.createCollection('crudCol');
    await col2.insertMany([
      { name: 'Alice', age: 25, address: 'Wonderland', type: 'en' },
      { name: 'Alice', age: 28, address: 'Old Wonderland', type: 'en' },
      { name: 'Bob', age: 30, address: 'Builderland', type: 'cn' },
      { name: 'Charlie', age: 35, address: 'Chocolate Factory', type: 'en' },
    ]);
    const uOne = await col2.updateOne({ name: 'Alice' }, { $set: { age: 29 } });
    const uMany = await col2.updateMany({ name: 'Alice' }, { $set: { address: 'Updated' } });
    const dOne = await col2.deleteOne({ name: 'Alice' });
    const dMany = await col2.deleteMany({ type: 'en' });
    const rest = await col2.find({}, { projection: { _id: 0, name: 1 } }).toArray();
    const actual2 = {
      uOneMatched: uOne.matchedCount,
      uManyModified: uMany.modifiedCount,
      dOneDeleted: dOne.deletedCount,
      dManyDeleted: dMany.deletedCount,
      remainingNames: rest.map((d) => d.name),
    };
    const expected2 = {
      uOneMatched: 1,
      uManyModified: 2,
      dOneDeleted: 1,
      dManyDeleted: 2,
      remainingNames: ['Bob'],
    };
    cases.push({
      name: 'update_and_delete_one_many',
      passed: JSON.stringify(actual2) === JSON.stringify(expected2),
      expected: expected2,
      actual: actual2,
    });

    // Case 3: sort_limit_skip_pagination
    const col3 = await db.createCollection('pageCol');
    await col3.insertMany([
      { name: 'Alice', age: 25 },
      { name: 'Bob', age: 30 },
      { name: 'Charlie', age: 35 },
      { name: 'Dave', age: 20 },
      { name: 'Eve', age: 22 },
    ]);
    const asc = await col3.find().sort({ age: 1 }).toArray();
    const desc = await col3.find().sort({ age: -1 }).toArray();
    const top3 = await col3.find().limit(3).toArray();
    const page2 = await col3.find().skip(2).limit(2).toArray();
    const actual3 = {
      ascAges: asc.map((d) => d.age),
      descAges: desc.map((d) => d.age),
      limit3Names: top3.map((d) => d.name),
      skip2Limit2Names: page2.map((d) => d.name),
    };
    const expected3 = {
      ascAges: [20, 22, 25, 30, 35],
      descAges: [35, 30, 25, 22, 20],
      limit3Names: ['Alice', 'Bob', 'Charlie'],
      skip2Limit2Names: ['Charlie', 'Dave'],
    };
    cases.push({
      name: 'sort_limit_skip_pagination',
      passed: JSON.stringify(actual3) === JSON.stringify(expected3),
      expected: expected3,
      actual: actual3,
    });

    // Case 4: lookup_left_join_drop_and_promise_chain
    const orders = db.collection('orders');
    const products = db.collection('products');
    await orders.insertMany([
      { _id: 1, product_id: 101, quantity: 2 },
      { _id: 2, product_id: 102, quantity: 1 },
      { _id: 3, product_id: 103, quantity: 4 },
      { _id: 4, product_id: 999, quantity: 1 },
    ]);
    await products.insertMany([
      { _id: 101, name: 'Product A', price: 50 },
      { _id: 102, name: 'Product B', price: 70 },
      { _id: 103, name: 'Product C', price: 100 },
      { _id: 104, name: 'Product D', price: 120 },
    ]);
    const joined = await orders
      .aggregate([
        {
          $lookup: {
            from: 'products',
            localField: 'product_id',
            foreignField: '_id',
            as: 'productDetails',
          },
        },
      ])
      .toArray();

    const dropOk = await db.collection('pageCol').drop();

    const docsCol = db.collection('documents');
    const ins = await docsCol.insertOne({ site: 'mbsky.example' });
    const afterIns = await docsCol.find({}).toArray();
    await docsCol.updateOne({ _id: ins.insertedId }, { $set: { site: 'updated.example' } });
    const afterUpd = await docsCol.findOne({ _id: ins.insertedId });
    await docsCol.deleteOne({ _id: ins.insertedId });
    const afterDel = await docsCol.find({}).toArray();

    const actual4 = {
      order1Product: joined[0].productDetails[0].name,
      unmatchedOrderDetailsCount: joined[3].productDetails.length,
      dropOk,
      promiseChainAfterInsertCount: afterIns.length,
      promiseChainUpdatedSite: afterUpd.site,
      promiseChainFinalCount: afterDel.length,
    };
    const expected4 = {
      order1Product: 'Product A',
      unmatchedOrderDetailsCount: 0,
      dropOk: true,
      promiseChainAfterInsertCount: 1,
      promiseChainUpdatedSite: 'updated.example',
      promiseChainFinalCount: 0,
    };
    cases.push({
      name: 'lookup_left_join_drop_and_promise_chain',
      passed: JSON.stringify(actual4) === JSON.stringify(expected4),
      expected: expected4,
      actual: actual4,
    });
  } finally {
    await client.close();
  }

  console.log(JSON.stringify({ version: process.version, cases }));
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
核对 mongodb:// URI 解析与投影隐藏 _id、updateOne/Many 与 deleteOne/Many 计数、sort/skip/limit 分页顺序、$lookup 命中与未命中左外连接,以及 drop() 和 Promise 全流程闭环。

查看独立实例 ↗ 在独立页面查看源码、运行环境与工程包

本地运行

解压后按 README 说明在对应本地环境运行脚本。

下载本章实验包 (mbskycom202612a1059.zip) ↓ 查看运行说明 ↗

本章附件与实例包

下载课程关联工程包:Node.js

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1059.zip

下载课程关联工程包:Node.js

课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a1041.zip

常见错误与边界检查

  • 实际端口、文档资源与应用配置都应和测试条件一致。

技术规范与官方资料

练习与参考解答

查看参考解答

不会被过滤掉。`$lookup` 遵循左外连接语义,会保留主集合的全部文档,并在 `as` 指定的输出字段中放入一个空数组 `[]`。

SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习