06nodejs如何连接mongodb

一、搭建环境:

 1、安装node环境
 2、安装mongodb
 3、在nodeJS的项目里安装模块:

    • 安装mongodb模块: npm i   mongodb
    • 安装mongoose : npm   i    mongoose

二、思路图:

      

三、代码:

  •     项目文件夹图:


  • 代码:
dbconn.js
//该文件(公共文件)的功能:链接数据库的代码
const mongoose = require("mongoose");

module.exports = mongoose.createConnection("10.35.165.187","db1708");
vipdb.js
//该文件的功能:针对集合(表)vips的所有的数据库操作

const dbconn = require("./dbconn");
const mongoose = require("mongoose");

//1、创建模板(对应于数据库中集合(表)结构)
let vipSchema = new mongoose.Schema({
   "username":String,
   "userpass":String,
   "age":Number
});

//2、创建模型model,把模板和数据库中的集合进行对应
let VipModel = dbconn.model("vips",vipSchema);

module.exports = {
    add:function (data,func) {
        //1、实体(要添加到数据库中数据(json对象))
        let vipEntity = new VipModel(data);
        vipEntity.save((err,data)=>{
            if(err){
                //console.log(err);
                func(false);
            }else{
                //console.log(data);
                func(true);
            }
        });
    },

}
reg.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>欢迎成为1708班的会员</title>
</head>
<body>
<h1>这是注册</h1>
    <form method="post" action="reg.do">
        用户名:<input type="text" name="username" value="jzm"/><br/>
        密码:<input type="password" name="userpass" value="123123" /><br/>
        确认密码:<input type="password" /><br/>
        年龄:<input type="text" name="age" value="0" /><br/>
        <input type="submit" value="注册">
    </form>
</body>
</html>
router.js
//该文件的功能:
// 1、web项目中服务器端所有功能函数,
const fs = require("fs");
const querystring = require("querystring");
const vipdb = require("./db/vipdb");


module.exports = {
    "html":function (filename,req,res) {
        fs.readFile(filename,"utf8",(err,data)=>{
            if(err){
                console.log(err);
            }else{
                res.statusCode = 200;
                res.setHeader("Content-type","text/html;charset=utf-8");
                res.write(data);
                res.end();
            }
        });
    },
    "do":function (filename,req,res) {
        //注册的处理
        //1、接收前端的数据
        let postStr = "";
        req.on("data",(chunk)=>{
            postStr+=chunk;
        });
        req.on("end",()=>{
            let queryObj = querystring.parse(postStr);
            console.log("服务器端拿到了前端发来的数据:"+queryObj.username+","+queryObj.userpass);
            //2、处理(链接数据库)
            vipdb.add({
                "username":queryObj.username,
                "userpass":queryObj.userpass,
                "age":queryObj.age
            },function (isSuccess) {
                //3、响应
                res.statusCode = 200;
                res.setHeader("Content-type","text/html;charset=utf-8");
                if(isSuccess){
                    res.write("亲,注册成功!");
                }else{
                    res.write("亲,注册失败!");

                }
                res.end();
            });
        });
    }
}
server.js
//该文件的功能是:
// 1、创建服务器,
// 2、接收请求,根据不同的请求调用不同的函数(函数都在router模块里)

const http = require("http");
const url = require("url");
const path = require("path");
const router = require("./router");

const server = http.createServer((req,res)=>{
    //根据前端请求url(发送的url),完成对应的功能
    let urlObj = url.parse(req.url);
    let pathname = urlObj.pathname.substring(1);

    if(pathname!="favicon.ico"){
        let ext = path.extname(pathname).substring(1);
         try{
             router[ext](pathname,req,res);
         } catch (err){

         }
    }
});

server.listen(706,"10.35.165.187",()=>{
    console.log("服务器启动成功");
});










  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值