mongoDB Demo完整版

const http = require('http');//服务器
const url = require('url');//路由功能
const mongoose = require('mongoose');//数据库
const querystring =require('querystring');  //转换字符串为对象
//各种引入
const app = http.createServer();//创建服务器
mongoose.connect('mongodb://localhost/playground', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => { console.log('数据库连接成功'); })
    .catch(() => { console.log('连接失败'); })
//以上是链接数据库
const UserSchema = new mongoose.Schema({
    name: {
        type: String,
        require: true,
        minlength: 2,
        maxlength: 20
    },
    age: {
        type: Number,
        min: 0,
        max: 1000
    },
    password: String,
    hobbies: [String]
})
//以上是创建集合规则

const User = mongoose.model('User', UserSchema);
//以上是创建集合

// mongoimport -d playground -c users --jsonArray ./data.json
//用于往数据库里导入数组类型的json文件

app.on('request', async (req, res) => {
    const method = req.method;//获取请求方式
    const { pathname,query } = url.parse(req.url,true);//获取请求路径

    if (method == 'GET') {
        if (pathname == '/list' ||pathname=='/') {//呈现列表页面
            let users = await User.find();//找到数据库里的数据!!使用异步函数,确保可以拿到数据....因为查询是耗时操作,会转到异步路径中.
            console.log(users);
            let list1 = `<!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Document</title>
            </head>
            <body>
                <a href="/add">添加用户</a>
                <table>
                    <tr>
                        <td>用户名</td>
                        <td>年龄</td>
                        <td>爱好</td>
                        <td>操作</td>
                    </tr>`;//把页面存储在变量中,之后用就好了....暴力
            //上面是找数据列表以上的值
            //中间是把数据库里的值传到html文件中去

            users.forEach(item => { //item是值的每个对象
                list1 += `
    <tr>
    <td>${item.name}</td>
    <td>${item.age}</td>    
    <td>`;//佛了,由于``中无法进行想要的循环,所以在次进行拆分

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

                list1 += ` 
    </td>
    <!-- <td>${item.password}</td> 这里是密码。后来加的,只为看下效果 -->
    <td>
        <a href="/remove?id=${item._id}">删除</a>
        <a href="/change?id=${item._id}">修改</a>
    </td>
</tr>
    `;//利用${item.val}显示了数据库里的值
            });

            //中间是把数据库里的值传到html文件中去
            //下面是复制列表以下的东西
            list1 += `
                </table>
                </body>
                </html>`;
            res.end(list1);
        }
        else if(pathname=='/add'){
            let add=`<!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Document</title>
            </head>
            <body>
                <h1>添加用户</h1>
                <form action="/add" method="post">
                    <label for="">密码</label>
                    <input type="text" name="password" id="" placeholder="请输入密码">
                    <label for="">名字</label>
                    <input type="text" name="name" id="" placeholder="请输入名字">
                    <label for="">年龄</label>
                    <input type="text" name="age" id="" placeholder="请输入年龄">
                    <label for="">选择爱好</label>
                    <input type="checkbox" value="aaa" name="hobbies">aaa
                    <input type="checkbox" value="123" name="hobbies">123
                    <input type="checkbox" value="dota" name="hobbies">dota
                    <input type="submit">
                </form>
            </body>
            </html>`;
            res.end(add);
        }else if(pathname=='/change'){//先把add的方法拿过来(因为修改和添加差不多)
            let user= await User.findOne({_id:query.id});//通过id获取到数据
            console.log(user);
            let hobbies=["aaa","123","dota"];
            let change=`<!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta http-equiv="X-UA-Compatible" content="IE=edge">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>Document</title>
            </head>
            <body>
                <h1>修改用户</h1>
                <form action="/change?id=${user._id}" method="post">
                    <label for="">密码</label>
                    <input value="${user.password}" type="text" name="password" id="" placeholder="请输入密码">
                    <label for="">名字</label>
                    <input value="${user.name}" type="text" name="name" id="" placeholder="请输入名字">
                    <label for="">年龄</label>
                    <input value="${user.age}" type="text" name="age" id="" placeholder="请输入年龄">
                    <label for="">选择爱好</label>`;

                    hobbies.forEach((item)=>{
                        let ishobby= user.hobbies.includes(item);    //返回T o F
                        if(ishobby){//判断是否被选中
                            change+=`
                            <input type="checkbox" value="${item}" checked>${item}
                            `;
                        }else{
                            change+=`<input type="checkbox" value="${item}">${item}`;
                        }
                    })

                    change+=`
                    <input type="submit">
                    </form>
                </body>
                </html>`;//添加路由。呈递修改页面STEP-1
            res.end(change);
        }else if(pathname=='/remove'){
            console.log(query.id);//先试下能否得到id
            await User.findOneAndDelete({_id:query.id});//删除方法
            res.writeHead(301,{
                location:'/list'
            });
            res.end();
        }
    } else if (method == 'POST') {
        if(pathname=='/add'){
            console.log('123');//测试下能不能到这里
            //1-接受提交信息
            let formdata='';
            req.on('data',(param)=>{  //多次data事件(有数据传输就会触发)
                formdata+=param;
            });
            req.on('end',async ()=>{      //一次end事件
                let user=querystring.parse(formdata);
                console.log('成功添加数据+1\n',querystring.parse(formdata));//在控制台测试,打印结果(字符串属性转换为了对象属性)
            //2-添加到数据库中
            await User.create(user);
            res.writeHead(301,{ //301代表重定向,location代表要跳转的地址
                location:'/list'
            });
            res.end();  //这个很重要,代表结束
            });
        }else if(pathname=="/change"){//复制粘贴上面的先
            console.log('123');//测试下能不能到这里
            //1-接受提交信息
            let formdata='';
            req.on('data',(param)=>{  //多次data事件(有数据传输就会触发)
                formdata+=param;
            });
            req.on('end',async ()=>{      //一次end事件
                let user=querystring.parse(formdata);
                console.log('成功修改数据+1\n',querystring.parse(formdata));//在控制台测试,打印结果(字符串属性转换为了对象属性)
            //2-添加到数据库中
            await User.updateOne({_id:query.id},user);//这里有改动,变为updateone属性
            res.writeHead(301,{ //301代表重定向,location代表要跳转的地址
                location:'/list'
            });
            res.end();  //这个很重要,代表结束
            });
        }
    };
});
app.listen(3000);
console.log('SUCCESS\nhttp://localhost:3000/');
//对响应做出反应



//笔记:
//想要后台更新数据,在命令行输入以下命令(重新引入数据文件)并删除旧的就行了,很是**,以后肯定会有更好的方法
// mongoimport -d playground -c users --jsonArray ./data.json

//怎样在这个文件中设立跳转?简单,把helf='add.html'换成'/add'就好了!!!!
//在from下添加action:/add   才能当点submit时候才会做到if(post)中的(pathname==’/add‘)


// 案例反思和总结:
// 1-首先,字符串拼接这些操作无需多次记忆,之后在学习模板引擎以后会很快的掌握
// 2-之后的学习重点会转向VUE,毕竟项目开始催了<OK,开始正式写反思>


// 3- { useNewUrlParser: true, useUnifiedTopology: true } 的使用,看命令行提不提示
// 4- const { pathname,query } = url.parse(req.url,true); 这个方法多次使用,注意!
// 5- async 和 await 注意,出现有读取,载入等要等待的(异步进程)就可以用了
// 6-使用异步函数,确保可以拿到数据....因为查询是耗时操作,会转到异步路径中.
// 7-利用${item.val}显示了数据库里的值
// 8-以后多看看post和get方法
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
package dzs.com.MongoDB; import java.util.ArrayList; import java.util.List; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.MongoClientURI; import com.mongodb.MongoCredential; import com.mongodb.ServerAddress; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; public class MongoDBJDBC { private static String uri ="mongodb://dzs:123456@127.0.0.1:27017/test"; @SuppressWarnings("deprecation") public static void main(String[] args){ try { //连接到MongoDB服务 如果是远程连接可以替换“localhost”为服务器所在IP地址 //ServerAddress()两个参数分别为 服务器地址 和 端口 ServerAddress serverAddress = new ServerAddress("localhost",27017); List<ServerAddress> addrs = new ArrayList<ServerAddress>(); addrs.add(serverAddress); //MongoCredential.createScramSha1Credential()三个参数分别为 用户名 数据库名称 密码 MongoCredential credential = MongoCredential.createScramSha1Credential("admin", "test", "123456".toCharArray()); List<MongoCredential> credentials = new ArrayList<MongoCredential>(); credentials.add(credential); //1、通过连接认证获取MongoDB连接 MongoClient mongoClient = new MongoClient(addrs,credentials); MongoDatabase mongoDatabase = mongoClient.getDatabase("test"); System.out.println("1--Connect to database successfully"); //2、通过uri方式连接MongoDB uri根据选择的数据库修改登录用户dzs MongoClientURI mongoClientUri =new MongoClientURI(uri); MongoClient mongoclient =new MongoClient(mongoClientUri); //连接到数据库 MongoDatabase mongoDatabase2 = mongoclient.getDatabase("test"); System.out.println("2--Connect to database successfully"); //使用test数据库,如果不存在会自动创建 MongoCollection<Document> collection = mongoDatabase2.getCollection("test"); System.out.println("集合 test 选择成功"); /**插入文档 * 1. 创建文档 org.bson.Document 参数为key-value的格式 * 2. 创建文档集合List<Document> * 3. 将文档集合插入数据库集合中 mongoCollection.insertMany(List<Document>) 插入单个文档可以用 mongoCollection.insertOne(Document) * */ Document document = new Document("title", "MongoDB"). append("description", "database"). append("likes", 100). append("by", "Fly"); List<Document> documents = new ArrayList<Document>(); documents.add(document); collection.insertMany(documents); System.out.println("文档插入成功"); /**检索所有文档 * 1. 获取迭代器FindIterable<Document> * 2. 获取游标MongoCursor<Document> * 3. 通过游标遍历检索出的文档集合 * */ FindIterable<Document> findIterable = collection.find(); MongoCursor<Document> mongoCursor = findIterable.iterator(); while (mongoCursor.hasNext()) { System.out.println(mongoCursor.next()); } System.out.println("检索所有文档成功"); //更新文档 将文档中likes=100的文档修改为likes=200 collection.updateMany(Filters.eq("likes", 100), new Document("$set", new Document("likes", 200))); //检索查看结果 findIterable = collection.find(); mongoCursor = findIterable.iterator(); while (mongoCursor.hasNext()) { System.out.println(mongoCursor.next()); } System.out.println("更新文档成功"); //删除符合条件的第一个文档 collection.deleteOne(Filters.eq("likes", 200)); //删除所有符合条件的文档 collection.deleteMany(Filters.eq("likes", 200)); //检索查看结果 findIterable = collection.find(); mongoCursor = findIterable.iterator(); while (mongoCursor.hasNext()) { System.out.println(mongoCursor.next()); } System.out.println("删除文档成功"); } catch (Exception e) { System.err.println( e.getClass().getName() + ": " + e.getMessage() ); } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值