技术 · 思考 · 实践 · 成长

首页/Node/正文

Node.js 操作 MongoDB:MongoDB 驱动 CRUD 实战

Node5 次阅读

Node 操作 MongoDB 用官方 mongodb 驱动。本文讲连接与 CRUD(MongoDB 语法见数据库系列),结尾附商品 API 小案例。

一、安装与连接

npm install mongodb
const { MongoClient, ObjectId } = require('mongodb');

const client = new MongoClient('mongodb://127.0.0.1:27017');
await client.connect();
const db = client.db('shop');
const users = db.collection('users');

二、CRUD

// 插入
const r = await users.insertOne({ name: 'Tom', age: 20 });
console.log(r.insertedId);                 // ObjectId

// 查询
await users.find({ age: { $gte: 18 } }).toArray();
await users.findOne({ _id: new ObjectId(id) });

// 更新
await users.updateOne(
    { _id: new ObjectId(id) },
    { $set: { age: 21 }, $inc: { views: 1 } }
);

// 删除
await users.deleteOne({ _id: new ObjectId(id) });

三、ObjectId(重点)

const { ObjectId } = require('mongodb');
new ObjectId('65f1a2b3c4d5e6f7a8b9c0d1');   // 字符串转对象
String(result.insertedId);                   // 对象转字符串
// URL 参数的 id 是字符串,查询前必须 new ObjectId(id)
// 否则查不到(类型不匹配)!

四、聚合与分页

// 聚合
const stats = await orders.aggregate([
    { $match: { status: 'paid' } },
    { $group: { _id: '$userId', total: { $sum: '$amount' } } },
    { $sort: { total: -1 } }
]).toArray();

// 分页
const rows = await products.find(filter)
    .sort({ created: -1 })
    .skip((page - 1) * size)
    .limit(size)
    .toArray();
const total = await products.countDocuments(filter);

五、Express 集成

// 中间件里挂 db
app.use(async (req, res, next) => {
    req.db = global.db;               // 启动时连好存全局
    next();
});

// 路由里用
app.get('/api/users', async (req, res) => {
    const rows = await req.db.collection('users').find().toArray();
    res.json(rows);
});

六、注意

  • 连接要复用(别每次请求 new MongoClient);
  • ObjectId 混淆是头号 bug(字符串要转换);
  • 更新/删除必须带条件(防全表);
  • 查询字段建索引(见 MongoDB 索引篇)。

七、小案例:商品 API

const express = require('express');
const { MongoClient, ObjectId } = require('mongodb');

const app = express();
app.use(express.json());

let products;
MongoClient.connect('mongodb://127.0.0.1:27017')
    .then(client => { products = client.db('shop').collection('products'); });

// 列表(分页 + 关键词)
app.get('/api/products', async (req, res) => {
    const page = +req.query.page || 1, size = +req.query.size || 10;
    const filter = req.query.kw ? { name: new RegExp(req.query.kw) } : {};
    const [rows, total] = await Promise.all([
        products.find(filter).skip((page-1)*size).limit(size).toArray(),
        products.countDocuments(filter)
    ]);
    res.json({ total, rows });
});

// 详情
app.get('/api/products/:id', async (req, res) => {
    const doc = await products.findOne({ _id: new ObjectId(req.params.id) });
    doc ? res.json(doc) : res.status(404).json({error: 'not found'});
});

// 创建 / 更新 / 删除
app.post('/api/products', async (req, res) => {
    const r = await products.insertOne({ ...req.body, created: new Date() });
    res.status(201).json({ id: r.insertedId });
});

app.listen(3000);

连接复用 + ObjectId 转换 + 分页 Promise.all 并发 + 状态码规范 —— Node + Mongo 的 API 标准骨架。

八、总结

mongodb 驱动 connect 后复用;ObjectId 必转换;聚合/分页/索引与 shell 语法一致;Express 集成挂 req.db 或封装 Model。

知识是抵御一切灾祸的盾牌

评论交流

0 条评论 · 支持多级回复
验证码
暂无评论,来说说你的想法吧

相关文章

继续阅读