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

发布于:2025-06-07 ⋅ 阅读:(19) ⋅ 点赞:(0)

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


1. MongoDB(NoSQL)写法

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. 增加错误处理
    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 检查字段(如果需要):
    const user = await db.collection('users').findOne({ email, emailVerified: { $exists: true } });
    

2. MySQL/SQL 写法

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(推荐)
    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 等库,避免回调写法:
    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(推荐)

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

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 操作。


网站公告

今日签到

点亮在社区的每一天
去签到