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

相关推荐
-SGlow-1 小时前
MySQL相关概念和易错知识点(3)(表内容的CURD、内置函数)
linux·运维·服务器·数据库·mysql
飞翔的佩奇1 小时前
基于SpringBoot+MyBatis+MySQL+VUE实现的经方药食两用服务平台管理系统(附源码+数据库+毕业论文+部署教程+配套软件)
数据库·vue.js·spring boot·mysql·毕业设计·mybatis·经方药食两用平台
bing_1582 小时前
在多租户或多服务共享 Redis 时,如何做逻辑隔离或权限控制?
数据库·redis·缓存
ChaITSimpleLove2 小时前
PostgreSQL 中删除指定数据库下的所有表结构
数据库·postgresql·bash·sql 脚本·.net npgsql
孫治AllenSun4 小时前
【Mysql】字段隐式转换对where条件和join关联条件的影响
数据库·mysql·oracle
生涯にわたる学び4 小时前
数据库02 网页html01 day44
数据库·html
2301_793086875 小时前
Mysql group by
数据库·mysql
jllllyuz6 小时前
Spring中的事务是如何实现的
数据库·sql·spring
wangmengxxw6 小时前
Spring-常用注解
java·数据库·spring·注解
m0_747266096 小时前
contentprovider实验+SQLite数据库的实现
数据库·sqlite