当前位置:   article > 正文

使用Node+MongoDB实现用户信息增删改查(带效果图)_node后端确认删除mongodb用户

node后端确认删除mongodb用户

先把代码放在这里,有空在详细说一下

原料/工具:

  • Node.js
  • MongoDB数据库
  • mongoose第三方模块

APP.js代码:

const http = require('http');
const mongoose = require('mongoose');
const url = require('url');
const querystring = require('querystring');

const app = http.createServer();
mongoose.connect('mongodb://127.0.0.1/playground', { useNewUrlParser: true, useUnifiedTopology: true })
  .then((result) => {
    console.log('数据库连接成功')
  })
  .catch(() => { console.log("数据库连接失败") });
const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 2,
    maxlength: 10
  },
  age: {
    type: Number,
    min: 10,
    max: 80
  },
  password: String,
  email: String,
  hobbies: [String]
});
const User = mongoose.model('User', userSchema);

app.on('request', async (req, res) => {
  //为服务器添加请求事件
  //req.on('request', async (result,err)=>{});
  //请求方法
  const method = req.method;
  //请求地址
  const { pathname, query } = url.parse(req.url, true);
  if (method == 'GET') {
    if (pathname == '/list' || pathname == '/') {
      //await只能在异步函数里面被使用
      let Users = await User.find();
      let list = `
                <!DOCTYPE html>
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                	<title>用户列表</title>
                	<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
                </head>
                <body>
                	<div class="container">
                		<h6>
                			<a href="/add" class="btn btn-primary">添加用户</a>
                		</h6>
                		<table class="table table-striped table-bordered">
                			<tr>
                				<td>用户名</td>
                				<td>年龄</td>
                				<td>爱好</td>
                				<td>邮箱</td>
                				<td>操作</td>
                			</tr>
                `;
      Users.forEach((item) => {
        list += `
                <tr>
				        <td>${item.name}</td>
                <td>${item.age}</td>
                <td>
                `;

        item.hobbies.forEach(item => {
          list += `<span>${item}</span>`;
        });


        list += `</td>
				<td>${item.email}</td>
				<td>
					<a href="/remove?id=${item._id}" class="btn btn-danger btn-xs">删除</a>
					<a href="/modify?id=${item._id}" class="btn btn-success btn-xs">修改</a>
				</td>
			    </tr>
                    `
      });

      list += `
                         </table>
                    </div>
                </body>
                </html>
                `;
      res.end(list);
    } else if (pathname == '/add') {
      let add = `<!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <title>用户列表</title>
                <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
            </head>
            <body>
                <div class="container">
                    <h3>添加用户</h3>
                    <form method="POST" action="/add">
                      <div class="form-group">
                        <label>用户名</label>
                        <input name='name' type="text" class="form-control" placeholder="请填写用户名">
                      </div>
                      <div class="form-group">
                        <label>密码</label>
                        <input name="password" type="password" class="form-control" placeholder="请输入密码">
                      </div>
                      <div class="form-group">
                        <label>年龄</label>
                        <input name="age" type="text" class="form-control" placeholder="请填写年龄">
                      </div>
                      <div class="form-group">
                        <label>邮箱</label>
                        <input name="email" type="email" class="form-control" placeholder="请填写邮箱">
                      </div>
                      <div class="form-group">
                        <label>请选择爱好</label>
                        <div>
                            <label class="checkbox-inline">
                              <input name="hobbies" type="checkbox" value="足球"> 足球
                            </label>
                            <label class="checkbox-inline">
                              <input name="hobbies" type="checkbox" value="篮球"> 篮球
                            </label>
                            <label class="checkbox-inline">
                              <input name="hobbies" type="checkbox" value="橄榄球"> 橄榄球
                            </label>
                            <label class="checkbox-inline">
                              <input name="hobbies" type="checkbox" value="敲代码"> 敲代码
                            </label>
                            <label class="checkbox-inline">
                              <input name="hobbies" type="checkbox" value="抽烟"> 抽烟
                            </label>
                            <label class="checkbox-inline">
                              <input name="hobbies" type="checkbox" value="喝酒"> 喝酒
                            </label>
                            <label class="checkbox-inline">
                              <input name="hobbies" type="checkbox" value="烫头"> 烫头
                            </label>
                        </div>
                      </div>
                      <button type="submit" class="btn btn-primary">添加用户</button>
                    </form>
                </div>
            </body>
            </html>`;
      res.end(add);
    } else if (pathname == '/modify') {
      let Usermsg = await User.findOne({ _id: query.id });
      let hobbies = ['足球', '篮球', '橄榄球', '敲代码', '抽烟', '喝酒', '烫头', '吃饭', '睡觉', '打豆豆'];
      console.log(Usermsg);
      //呈现修改页面
      let modify = `<!DOCTYPE html>
          <html lang="en">
          <head>
              <meta charset="UTF-8">
              <title>用户列表</title>
              <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@3.3.7/dist/css/bootstrap.min.css">
          </head>
          <body>
              <div class="container">
                  <h3>修用户</h3>
                  <form method="POST" action="/modify?id=${Usermsg._id}">
                    <div class="form-group">
                      <label>用户名</label>
                      <input name='name' value="${Usermsg.name}" type="text" class="form-control" placeholder="请填写用户名">
                    </div>
                    <div class="form-group">
                      <label>密码</label>
                      <input name="password" value="${Usermsg.password}" type="password" class="form-control" placeholder="请输入密码">
                    </div>
                    <div class="form-group">
                      <label>年龄</label>
                      <input name="age" value="${Usermsg.age}" type="text" class="form-control" placeholder="请填写年龄">
                    </div>
                    <div class="form-group">
                      <label>邮箱</label>
                      <input name="email" value="${Usermsg.email}" type="email" class="form-control" placeholder="请填写邮箱">
                    </div>
                    <div class="form-group">
                      <label>请选择爱好</label>
                      <div>

                      `;

      hobbies.forEach(item => {
        // 判断当前循环项在不在用户的爱好数据组
        let isHobby = Usermsg.hobbies.includes(item);
        if (isHobby) {
          modify += `
                  <label class="checkbox-inline">
                    <input type="checkbox" value="${item}" name="hobbies" checked> ${item}
                  </label>
                `
        } else {
          modify += `
                  <label class="checkbox-inline">
                    <input type="checkbox" value="${item}" name="hobbies" > ${item}
                  </label>
                `
        }
      });
      modify += `
            </div>
                    </div>
                    <button type="submit" class="btn btn-primary">修改用户</button>
                  </form>
              </div>
          </body>
          </html>
          `
      res.end(modify);
    }else if(pathname == '/remove'){
      await User.findOneAndDelete({_id:query.id});
      res.writeHead(301, { Location: '/list' });
      res.end();
    }
  } else if (method == 'POST') {
    if (pathname == '/add') {
      let fromdata = "";
      //接收post参数
      req.on('data', param => {
        fromdata += param;
      });
      //post参数接收完毕
      req.on('end', async () => {
        // console.log(querystring.parse(fromdata));
        let user = querystring.parse(fromdata);
        await User.create(user);
      });
      res.writeHead(301, { Location: '/list' });
      res.end();
    } else if (pathname == '/modify') {
      let fromdata = "";
      //接收post参数
      req.on('data', param => {
        fromdata += param;
      });
      //post参数接收完毕
      req.on('end', async () => {
        // console.log(querystring.parse(fromdata));
        let user = querystring.parse(fromdata);
        await User.updateOne({ _id: query.id }, user);
      });
      res.writeHead(301, { Location: '/list' });
      res.end();
    }
  };

  res.end("ok")
});
app.listen(3000);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247
  • 248
  • 249
  • 250
  • 251
  • 252
  • 253
  • 254
  • 255
  • 256
  • 257

运行代码,当前文件夹下输入:

node app.js
  • 1

浏览器访问地址:

localhost:3000
  • 1

效果图:

用户信息增删改查

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/118880
推荐阅读
相关标签
  

闽ICP备14008679号