连接数据库

NodeJS

mongoose 用于连接 mongodb 数据库
sequelize 用于连接 MySQL 类的关系型数据库

使用mongoose

1、安装

$ npm i mongoose

2、nodejs 中链接数据库
只是举例,演示数据库连接具体流程

//引入mongoose
const mongoose = require('mongoose');
//连接数据库
mongoose.connect('mongodb://127.0.0.1:27017/数据库名称')
//mongoose 使用到的用户模型
const Cat = mongoose.model('Cat', { name: String });
//根据用户模型,创建待保存到数据库中的用户对象
const kitty = new Cat({ name: 'Zildjian' });
//保存到数据库中
kitty.save().then(() => console.log('meow'));

API 文档

3、在之前的基础之上,链接数据库
app.js

// 引入 mongoose
const mongoose = require('mongoose')
//连接数据库
mongoose.connect('mongodb://127.0.0.1:27017/test')
// 引入模型
const User = require('./models/user')

//实现注册,往数据库里添加数据的同时检查是否存在相同用户名
app.post('/register.do', (req, res) => {
    // 请求主体中获取登录用户信息
    const {username, password} = req.body
    /* 将注册用户的用户名与密码保存到数据库中 */
    // 在保存到数据库之前,先查询数据库的集合中是否已存在当前待注册用户的用户名
    User
    	//查找数据库里的username
      .find({username})
      .then(data => {
        console.log('查找:', data)
        // 根据查找结果处理
        if (data.length > 0) { // 已存在当前用户名的数据
          res.send('用户名已存在,不能继续注册...')
          return
        }
  
        // 根据 User 用户模型,创建待保存到数据库中的用户对象
        const user = new User({
          username,
          password,
        })
        // 保存到数据库中
        user.save().then((data) => {
          console.log('成功:', data)
          res.send(JSON.stringify(data))
        })
        //捕获异常
		.catch((err) => {
          console.log('失败:', err)
          res.send('用户注册失败!!!')
        })
      })
  })

user.js

//用户数据模型
const mongoose = require('mongoose')

/**
 * 用户数据结构(Schema)
 */
const userSchema = new mongoose.Schema({
  username: String,
  password: String,
})
/**
 * 根据用户数据结构,创建用户模型。
 * 创建出来的模型会关联到数据库的集合中
 * mongoose.model('User', userSchema) 如果不传递集合名称参数,通常以模型名称小写单词后加s变成复数作为集合名称
 */
const User = mongoose.model('User', userSchema)

// 导出用户模型,以便于其它模块中能够继续使用
module.exports = User

相关前端静态资源:
register.html

<body>
  <h3>用户注册</h3>

  <form action="/register.do" method="post">
    <div>用户名: <input type="text" name="username" value="xiaoming"></div>
    <div>密 码: <input type="text" name="password" value="123456"></div>
    <div><input type="submit" value="注册"></div>
  </form>
</body>

4、我的目录
在这里插入图片描述
其中的 fail.html , success.html 是 login.html 登录失败和成功跳转的页面,与注册页面无关。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值