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

相关推荐
u***32434 分钟前
Mysql官网下载Windows、Linux各个版本
linux·数据库·mysql
i***39585 分钟前
mysql之如何获知版本
数据库·mysql
Tzarevich14 分钟前
AIGC 时代,用自然语言操作 SQLite3 数据库
数据库·sqlite
r***013814 分钟前
MySQL最多能有多少连接
数据库·mysql
l***0636 分钟前
Redis--模糊查询--方法实例
数据库·redis·缓存
七烦1 小时前
金仓KingbaseES数据库安装至Linux系统
数据库·mysql·kingbasees
r***R2891 小时前
MySQL的日期时间类型
数据库·mysql
十五喵1 小时前
智慧物业|物业管理|基于SprinBoot+vue的智慧物业管理系统(源码+数据库+文档)
java·前端·数据库·vue.js·spring boot·毕设·智慧物业管理系统
b***67641 小时前
如何使用 SQL CREATE TABLE 创建一个表
数据库·sql·oracle
p***97611 小时前
完美解决phpstudy安装后mysql无法启动
数据库·mysql