不同的数据库操作方式:MongoDB(NoSQL)和 MySQL/SQL

这两种写法分别使用了不同的数据库操作方式:第一种是 MongoDB(NoSQL) 的写法,第二种是 MySQL/SQL 的写法。我们来对比它们的区别,并给出优化建议。


1. MongoDB(NoSQL)写法

javascript 复制代码
const user = await db.collection('users').findOne({ email });
if (!user) {
  return res.status(404).json({ status: 'fail', message: '用户不存在' });
}
await db.collection('users').updateOne({ email }, { $set: { emailVerified: true } });

特点

  • 异步 await 语法 :使用 Promise 风格,代码更清晰。
  • MongoDB 查询方式
    • findOne({ email }):查询单个用户(基于 email 字段)。
    • updateOne({ email }, { $set: { emailVerified: true } }):更新 emailVerified 字段。
  • 返回 JSON 响应 :如果用户不存在,返回 404 状态码和错误信息。

优化建议

  1. 增加错误处理

    javascript 复制代码
    try {
      const user = await db.collection('users').findOne({ email });
      if (!user) {
        return res.status(404).json({ status: 'fail', message: '用户不存在' });
      }
      await db.collection('users').updateOne({ email }, { $set: { emailVerified: true } });
      res.json({ status: 'success', message: '邮箱验证成功' });
    } catch (err) {
      res.status(500).json({ status: 'error', message: '服务器错误' });
    }
  2. 使用 $exists 检查字段 (如果需要):

    javascript 复制代码
    const user = await db.collection('users').findOne({ email, emailVerified: { $exists: true } });

2. MySQL/SQL 写法

javascript 复制代码
db.query(`SELECT * FROM users WHERE openid = ?`, [openid], (err, results) => {
  if (err) throw err;
  if (results.length === 0) {
    return res.status(404).json({ status: 'fail', message: '用户不存在' });
  }
  db.query(`UPDATE users SET emailVerified = 1 WHERE openid = ?`, [openid], (err) => {
    if (err) throw err;
    res.json({ status: 'success', message: '邮箱验证成功' });
  });
});

特点

  • 回调函数风格db.query(sql, [params], callback),容易形成"回调地狱"。
  • SQL 语句
    • SELECT * FROM users WHERE openid = ?:查询用户(? 是参数占位符)。
    • UPDATE users SET emailVerified = 1 WHERE openid = ?:更新 emailVerified 字段(1 表示 true)。
  • 错误处理if (err) throw err; 直接抛出错误(不够友好)。

优化建议

  1. 改用 async/await(推荐)

    javascript 复制代码
    try {
      const [rows] = await db.query(`SELECT * FROM users WHERE openid = ?`, [openid]);
      if (rows.length === 0) {
        return res.status(404).json({ status: 'fail', message: '用户不存在' });
      }
      await db.query(`UPDATE users SET emailVerified = 1 WHERE openid = ?`, [openid]);
      res.json({ status: 'success', message: '邮箱验证成功' });
    } catch (err) {
      res.status(500).json({ status: 'error', message: '服务器错误' });
    }
  2. 使用 mysql2/promiseknex.js 等库 ,避免回调写法:

    javascript 复制代码
    import mysql from 'mysql2/promise';
    const db = await mysql.createConnection({ ... });

3. 主要区别对比

特性 MongoDB(NoSQL) MySQL(SQL)
查询方式 findOne({ email }) SELECT * FROM users WHERE email = ?
更新方式 updateOne({ email }, { $set: { ... } }) UPDATE users SET emailVerified = 1 WHERE email = ?
错误处理 try/catch 回调或 try/catch(推荐)
异步风格 Promiseawait 回调或 Promise(推荐 mysql2/promise
适用场景 非结构化数据(JSON) 结构化数据(关系型数据库)

4. 最终推荐写法

MongoDB(推荐)

javascript 复制代码
try {
  const user = await db.collection('users').findOne({ email });
  if (!user) {
    return res.status(404).json({ status: 'fail', message: '用户不存在' });
  }
  await db.collection('users').updateOne({ email }, { $set: { emailVerified: true } });
  res.json({ status: 'success', message: '邮箱验证成功' });
} catch (err) {
  res.status(500).json({ status: 'error', message: '服务器错误' });
}

MySQL(推荐 async/await

javascript 复制代码
try {
  const [rows] = await db.query(`SELECT * FROM users WHERE email = ?`, [email]);
  if (rows.length === 0) {
    return res.status(404).json({ status: 'fail', message: '用户不存在' });
  }
  await db.query(`UPDATE users SET emailVerified = 1 WHERE email = ?`, [email]);
  res.json({ status: 'success', message: '邮箱验证成功' });
} catch (err) {
  res.status(500).json({ status: 'error', message: '服务器错误' });
}

总结

  • MongoDB 适合 JSON 数据,查询方式更灵活。
  • MySQL 适合结构化数据,推荐 async/await 避免回调地狱。
  • 错误处理 应该统一用 try/catch,返回合适的 HTTP 状态码(404500)。
  • SQL 注入防护 :MySQL 使用 ? 占位符,MongoDB 自动防注入。

如果你的项目已经使用 MySQL,可以考虑 ORM(如 Sequelize、TypeORM)Query Builder(如 Knex.js) 来简化 SQL 操作。

相关推荐
潘yi.2 小时前
NoSQL之Redis配置与优化
数据库·redis·nosql
zdkdchao2 小时前
hbase资源和数据权限控制
大数据·数据库·hbase
伤不起bb2 小时前
NoSQL 之 Redis 配置与优化
linux·运维·数据库·redis·nosql
leo__5202 小时前
PostgreSQL配置文件修改及启用方法
数据库·postgresql
南風_入弦4 小时前
优化09-表连接
数据库·oracle
Snk0xHeart5 小时前
极客大挑战 2019 EasySQL 1(万能账号密码,SQL注入,HackBar)
数据库·sql·网络安全
····懂···5 小时前
数据库OCP专业认证培训
数据库·oracle·ocp
学习中的码虫6 小时前
数据库-MySQL
数据库
Karry的巡洋舰6 小时前
【数据库】安全性
数据库·oracle
软件测试小仙女7 小时前
鸿蒙APP测试实战:从HDC命令到专项测试
大数据·软件测试·数据库·人工智能·测试工具·华为·harmonyos