不同的数据库操作方式: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 操作。

相关推荐
qq_192779876 小时前
高级爬虫技巧:处理JavaScript渲染(Selenium)
jvm·数据库·python
u0109272716 小时前
使用Plotly创建交互式图表
jvm·数据库·python
爱学习的阿磊6 小时前
Python GUI开发:Tkinter入门教程
jvm·数据库·python
tudficdew7 小时前
实战:用Python分析某电商销售数据
jvm·数据库·python
sjjhd6527 小时前
Python日志记录(Logging)最佳实践
jvm·数据库·python
Configure-Handler8 小时前
buildroot System configuration
java·服务器·数据库
2301_821369618 小时前
用Python生成艺术:分形与算法绘图
jvm·数据库·python
电商API_180079052479 小时前
第三方淘宝商品详情 API 全维度调用指南:从技术对接到生产落地
java·大数据·前端·数据库·人工智能·网络爬虫
2401_832131959 小时前
Python单元测试(unittest)实战指南
jvm·数据库·python
打工的小王10 小时前
redis(四)搭建哨兵模式:一主二从三哨兵
数据库·redis·缓存