Nodejs+MongoDB 增删改查

目录

一、Mongodb插入数据 

二、Mongodb导入数据 

三、Mongodb数据库查询文档 

四、Mongodb数据库删除文档 

五、Mongodb数据库更新文档  

六、集合关联 

七、实例 


一、Mongodb插入数据 

//连接数据库
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/playground',{useNewUrlParser:true,useUnifiedTopology: true})
    .then(()=>console.log('数据库连接成功'))
    .catch((err)=>console.log(err,'数据库连接失败'))

//创建规则集合
const courseSchema = new mongoose.Schema({
    name: String,
    author: String,
    isPublished: Boolean
});

// 使用规则创建集合
// 1.集合名称
// 2.集合规则
const Course = mongoose.model('Course', courseSchema) //coures
//第一种数据插入方式
/*const course = new Course({
    name:'Nodejs学习',
    author:'CXC',
    isPublished: true
})
course.save();*/

//第二种数据插入方式
Course.create({name:'前端学习', author: 'cxc', isPublished: false},(err,result)=>{
    console.log(err);
    console.log(result)
})

Course.create({name:'前端学习1', author: 'cxc', isPublished: false})
    .then(result=>console.log(result))
    .catch(err=>console.log(err))

MongoDB Compass 内显示已成功插入数据

 

二、Mongodb导入数据 

  1. 找到MongoDB安装文件夹下的mongoimport 文件;
  2. D:\Program Files\MongoDB\Server\4.2\bin ;
  3. 在系统环境变量path中添加该路径;
  4. 使用mongoimport –d 数据库名称 –c 集合名称 --file 要导入的文件位置以及名称;

     5.导入成功

 

三、Mongodb数据库查询文档 

.find({})  返回数组形式,返回一组文档

.findOne({})  返回一条文档 默认返回当前集合中第一条文档

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:/playground',{useNewUrlParser: true,useUnifiedTopology: true})
.
then(()=>console.log('数据库连接成功'))
.
catch(err=>console.log(err,'数据库连接失败'))

const userSchema = new mongoose.Schema({
   
name:String,
   
age:Number,
   
email:String,
   
hobbies:[String]
})


const User = mongoose.model('User',userSchema)
//查询用户集合中的所有文档
//User.find().then(result=>console.log(result))

User.find({_id: '5c09f236aeb04b22f8460967'}).then(result=>console.log(result))

//默认返回当前集合中第一条文档
//User.finOne().then(result=>console.log(result));
User.findOne({_id: '5c09f236aeb04b22f8460967'}).then(result=>console.log(result));

 

四、Mongodb数据库删除文档 

const User = mongoose.model('User',userSchema);
//删除单个 如果有多个,则删除第一个匹配项
User.findOneAndDelete({hobbies:'打豆豆'}).then((result)=>console.log(result))
//删除多个
User.deleteMany().then((result)=>console.log(result))

五、Mongodb数据库更新文档  

const User = mongoose.model('User',userSchema);

//更新单个 如果有多个,则更新第一个匹配项
User.updateOne({name:'狗蛋'},{name:'狗剩'})
    .
then((result)=>console.log(result))
//更新多个
User.updateMany({},{name:'陈六'})
    .
then((result)=>console.log(result))

六、集合关联 

       通常不同集合的数据之间是有关系的,例如文章信息和用户信息存储在不同集合中,文章是某个用户发表的,要查询文章的所有信息包括发表用户,就需要用到集合关联。

  • 使用id对集合进行关联;
  • 使用populate方法进行关联集合查询。

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:/playground', { useNewUrlParser: true,useUnifiedTopology: true })
        .
then(()=>console.log('数据库连接成功'))
        .
catch(err=>console.log(err,'数据库连接失败'))

const userSchema = new mongoose.Schema({
   
name: {
       
type:String,
       
required:true
   
},
   
age:Number
})
const postSchema = new mongoose.Schema({
   
title:String,
   
author:{
       
type:mongoose.SchemaTypes.ObjectId,
        
ref:'User1' //绑定User1
   
}
})

const User = mongoose.model('User1',userSchema);
const
Post = mongoose.model('Post1',postSchema);
User.create({name:'cxc',age:18}).then(result=>console.log(result));
Post.create({title:'nodejs',author: '5ebc05d390cb9304b424aa00'}).then(result=>console.log(result))
Post.
find().populate('author').then(result=>console.log(result)) //通过关联查询出用户姓名、年龄

七、实例 

 

/*  未使用模板引擎 
1.  搭建网站服务器,实现客户端与服务端的通信;
2. 连接数据库,创建用户集合,向集合中插入文档;
3. 当用户访问/list时,将所有用户信息查询出来;
        //实现路由功能
        //呈现用户列表界面
        //从数据库中查询用户信息 将用户信息展示在列表中
4. 将用户信息和表格HTML进行拼接并将结果响应回客户端;
5. 当用户访问/add时,呈现表单界面,并实现添加用户信息功能;
6. 当用户访问/modify时,呈现修改页面,并实现修改用户信息功能;
        //增加页面路由 呈现页面
            //在点击修改按钮的时候,将用户ID传递到当前页面
            //从数据库中查询当前用户信息,将用户信息展示到页面中
        //实现用户修改功能
            //指定表单的提交地址以及请求方式
            //接收客户端传递过来的用户信息 找到用户 将用户更新
7. 当用户访问/delete时,实现用户删除功能。
*/

const http = require('http');
const app = http.createServer();
const url = require('url');
const queryString = require('querystring');

require('./model/index');   
const User = require('./model/user');


app.on('request',async (req,res)=>{
    const method = req.method;
    const {pathname,query} = url.parse(req.url,true);

    if(method == 'GET') {
        if (pathname == '/list') {
            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>${item.email}</td>
                    <td>
                    <a href="/delete?id=${item._id}" class="btn btn-danger btn-xs">删除</a>
                    <a href="/modify?id=${item._id}" class="btn btn-success btn-xs">修改</a>
                    </td>`
            })
            list += ` </tr>
                    </table>
                    </div>
                    </body>
                    </html>`
            res.end(list);
        } else if (pathname == '/add') {
            let add = `<!DOCTYPE html>;
                        <html lang="en">
                        <head>
                        \t<meta charset="UTF-8">
                        \t<title>用户列表</title>
                        \t<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 type="checkbox" value="足球" name="hobbies"> 足球
                        </label>
                        <label class="checkbox-inline">
                          <input type="checkbox" value="篮球" name="hobbies"> 篮球
                        </label>
                        <label class="checkbox-inline">
                          <input type="checkbox" value="橄榄球" name="hobbies"> 橄榄球
                        </label>
                        <label class="checkbox-inline">
                          <input type="checkbox" value="敲代码" name="hobbies"> 敲代码
                        </label>
                        <label class="checkbox-inline">
                          <input type="checkbox" value="抽烟" name="hobbies"> 抽烟
                        </label>
                        <label class="checkbox-inline">
                          <input type="checkbox" value="喝酒" name="hobbies"> 喝酒
                        </label>
                        <label class="checkbox-inline">
                          <input type="checkbox" value="烫头" name="hobbies"> 烫头
                        </label>
                            </div>
                          </div>
                         <button type="submit" class="btn btn-primary">添加用户</button>
                        </form>
                        </div>
                        </body>
                        </html>`;
            res.end(add);
        }
        else if (pathname == '/modify') {
            let user = await User.findOne({_id: query.id});
            let hobbies = ['足球', '篮球', '橄榄球', '敲代码', '抽烟', '烫头'];
            let modify = `<!DOCTYPE html>
                        <html lang="en">
                        <head>
                        \t<meta charset="UTF-8">
                        \t<title>用户列表</title>
                        \t<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=${user._id}">
                          <div class="form-group">
                            <label>用户名</label>
                            <input value="${user.name}" name="name" type="text" class="form-control" placeholder="请填写用户名">
                          </div>
                          <div class="form-group">
                            <label>密码</label>
                            <input value="${user.password}" name="password" type="password" class="form-control" placeholder="请输入密码">
                          </div>
                          <div class="form-group">
                            <label>年龄</label>
                            <input value="${user.age}" name="age" type="text" class="form-control" placeholder="请填写邮箱">
                          </div>
                          <div class="form-group">
                            <label>邮箱</label>
                            <input value="${user.email}" name="email" type="email" class="form-control" placeholder="请填写邮箱">
                          </div>
                          <div class="form-group">
                            <label>请选择爱好</label>
                            <div>
                          `;
            hobbies.forEach(item => {
                if (user.hobbies.includes(item)) {
                    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 == '/delete') {
            await User.findOneAndDelete({_id: query.id});
            res.writeHead(301,{
                Location:'/list'
            })
            res.end();
        }
    }
        else if (method == 'POST') {
            if (pathname == '/add') {
                let formData = '';
                req.on('data', param => {
                    formData += param;
                });
                req.on('end', async () => {
                    let user = queryString.parse(formData);
                    await User.create(user);
                    res.writeHead(301, {
                        Location: '/list'
                    })
                    res.end();

                });
            } else if (pathname == '/modify') {
                let formData = '';
                req.on('data', param => {
                    formData += param;
                });
                req.on('end', async () => {
                    let user = queryString.parse(formData);
                    await User.updateOne({_id: query.id}, user);
                    res.writeHead(301, {
                        Location: '/list'
                    })
                    res.end();
                });
            }
        }

})
app.listen(3000);
console.log('服务器部署成功')
  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MySQL、MongoDB和Redis都是流行的开源数据库软件。 MySQL是一种关系型数据库管理系统(RDBMS),广泛被用于Web应用程序和其他需要可靠数据存储的项目。它使用结构化询语言(SQL)作为其询语言,支持大规模数据存储和高效的数据检索。MySQL的优点包括可靠性、灵活性和广泛的社区支持。它可以处理大量的数据,因此适用于大型企业和复杂的数据处理需求。 MongoDB是一种NoSQL数据库,以其灵活性和可扩展性而闻名。它是一个面向文档的数据库,使用类似JSON的文档来存储数据。这个特点使得MongoDB能够轻松地存储和询复杂的非结构化数据。MongoDB适用于大多数Web应用程序,特别是需要处理大量数据和具有快速读写需求的项目。 Redis是一种高速的内存数据存储系统,用于缓存和数据库应用程序。它被广泛应用于Web应用程序中的高速缓存需求,如页面缓存、会话存储和消息队列。Redis支持多种数据结构,如字符串、列表、集合和有序集合,并提供了丰富的API来处理这些结构。由于Redis将数据存储在内存中,它具有出色的性能和低延迟。 综上所述,MySQL、MongoDB和Redis都有各自的优点和适用场景。MySQL适用于需要可靠和结构化数据存储的项目,而MongoDB适合于非结构化和高度可扩展的数据,Redis则适用于高速缓存和内存数据存储需求。根据具体的项目需求和性能要求,选择适合的数据库软件可以提高数据存储和处理的效率。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值