MongoDB应用

本文涉及的产品
云数据库 MongoDB,通用型 2核4GB
简介: 初始化路由模板数据库和前端页面交互编写注册的后台接口先连接数据库和前台进行数据交互文章的后台接口先查询所有的文章内容发文章一些验证方法邮箱验证用户名随机生成

文章目录

初始化路由模板

  1. 1.在 router 文件夹中,新建 user.js 文件,作为用户的路由模块,并初始化代码如下:
const express = require('express')
// 创建路由对象
const router = express.Router()
// 注册新用户
router.post('/reguser', (req, res) => {
res.send('reguser OK')
})
// 登录
router.post('/login', (req, res) => {
res.send('login OK')
})
// 将路由对象共享出去
module.exports = router
  1. 2.在 app.js 中,导入并使用 用户路由模块 :
/ 导入并注册用户路由模块
const userRouter = require('./router/user')
app.use('/api', userRouter)
  1. 3.在 /router_handler/user.js 中,使用 exports 对象,分别向外共享如下两个 路由处理函
    数 :
**
* 在这里定义和用户相关的路由处理函数,供 /router/user.js 模块进行调用
*/
// 注册用户的处理函数
exports.regUser = (req, res) => {
res.send('reguser OK')
}
// 登录的处理函数
exports.login = (req, res) => {
res.send('login OK')
}
  1. 4.将 /router/user.js 中的代码修改为如下结构:
const express = require('express')
const router = express.Router()
// 导入用户路由处理函数模块
const userHandler = require('../router_handler/user')
// 注册新用户
router.post('/reguser', userHandler.regUser)
// 登录
router.post('/login', userHandler.login)
module.exports = router

数据库和前端页面交互


编写注册的后台接口


先连接数据库

  //插入新用户
    const mongoose = require('mongoose');
    //连接mongodb服务
    mongoose.connect('mongodb://127.0.0.1:27017/login');
    mongoose.connection.once('open', () => {
        let LoginSchema = new mongoose.Schema({
            name: {
                type: String,
            },
            password: String
        });
        let LoginModel = mongoose.model('persons', LoginSchema);
        LoginModel.create({
            name: userinfo.name,
            password: userinfo.password
        }, (err, data) => {
            if (err) {
                console.log(err);
                res.send({
                    status: 1,
                    message: '注册失败,用户名已存在!'
                })
            }
            res.send({
                status: 0,
                message: '成功注册!欢迎:'+PeapleName
            })
            mongoose.disconnect();
        })
    });
}


和前台进行数据交互

  xhr.open('POST', 'http://127.0.0.1:3007/api/reguser')
                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                xhr.send('name=' + ResVal + '&password=' + ResVal1)
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        if (xhr.status >= 200 && xhr.status < 300) {
                            const response = JSON.parse(xhr.response)
                            if (response.status == 0) {
                                alert(response["message"]);
                                window.location.href = "login"
                            } else {
                                alert(response["message"]);
                            }
                        }
                    }
                }

文章的后台接口

先查询所有的文章内容

exports.findAllarticle = (req,res)=>{
    //1.引入mongoose
    const mongoose = require('mongoose');
    //2.链接mongodb数据库 connect 连接
    mongoose.connect('mongodb://127.0.0.1:27017/article');
    //4.声明文档结构
    const ArticleSchema = new mongoose.Schema({
        content:String,
        title:String
    })
    //6.创建模型对象
    const ArticleModel = mongoose.model('aiticle', ArticleSchema);
    ArticleModel.find(function (err, data) {
        if(err) {
            res.send({
                status:1,
                msg:'查询失败!'
            })
        }else{
            res.send({
               status:0,
                data:data,
                msg:'查询成功'
            })
        }
    }
    )
}
  //查询数据库渲染页面
            const xhr = new XMLHttpRequest();
            xhr.open('POST', 'http://127.0.0.1:3007/find/findall')
            xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            xhr.send()
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status >= 200 && xhr.status < 300) {
                        const response = JSON.parse(xhr.response)
                        if (response.status == 0) {
                            const data = response['data']
                            for (let i = 0; i < data.length; i++) {
                                res = data[i]
                                var li = document.createElement('li')
                                content.appendChild(li)
                                li.innerHTML = `<a href='#'>` + `<h1>` + res["title"] + `</h1>` + `<br>` + res["content"] + `</a>` + `<br>` + "来自id为:" + str + "发布的文章" + `&nbsp` + "时间是:" + nowTime
                                var contents = document.querySelectorAll('.content ul li')
                                for (let i = 0; i < contents.length; i++) {
                                    contents[i].addEventListener('click', function () {
                                        var about = res["_id"]
                                        window.location.href = "content?" + encodeURIComponent(about)
                                    })
                                }
                            }
                        } else {
                            alert(response["msg"]);
                        }
                    }
                }
            }

发文章

// 发布新文章的处理函数
exports.addArticle = (req, res) => {
    const article = req.body
    //1.引入mongoose
    const mongoose = require('mongoose');
    //2.链接mongodb数据库 connect 连接
    mongoose.connect('mongodb://127.0.0.1:27017/article');
    //4.声明文档结构
    const ArticleSchema = new mongoose.Schema({
        content: String,
        title:String,
        author:String
    })
    //6.创建模型对象
    const ArticleModel = mongoose.model('aiticle', ArticleSchema);
    ArticleModel.create({
        content: article.content,
        title:article.title,
        author:article.author
    }, function (err, data) {
        if(err) {
            res.send({
                status:1,
                msg:'发布失败!'
            })
        }else{
            res.send({
               status:0,
                data:data.content,
                title:data.title,
                id:data.id,
                msg:'发布成功!'
            })
        }
        console.log(err);
        return
    }
    )
}
  const xhr = new XMLHttpRequest();
                xhr.open('POST', 'http://127.0.0.1:3007/my/article/add')
                xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
                xhr.send('content=' + fabuText.value + '&title=' + title.value+'&author='+str)
                xhr.onreadystatechange = function () {
                    if (xhr.readyState === 4) {
                        if (xhr.status >= 200 && xhr.status < 300) {
                            const response = JSON.parse(xhr.response)
                            if (response.status == 0) {
                                var li = document.createElement('li')
                                content.appendChild(li)
                                li.innerHTML = `<a href='#'>` + `<h1>` + response["title"] + `</h1>` + `<br>` + response["data"] + `</a>` + `<br>` + "来自用户为:" + str + "发布的文章" + `&nbsp` + "时间是:" + nowTime
                                fabuText.value = null
                                title.value = null
                                alert(response["msg"])
                                var contents = document.querySelectorAll('.content ul li')
                                for (let i = 0; i < contents.length; i++) {
                                    contents[i].addEventListener('click', function () {
                                        var about = response["id"]
                                        window.location.href = "content?" + encodeURIComponent(about)
                                    })
                                }
                            } else {
                                alert(response["msg"]);
                            }
                        }
                    }
                }

一些验证方法

邮箱验证

function isEmail(str){
    var reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
    return reg.test(str)
}

用户名随机生成

//1.先定义时间函数
 function timestampToTime(times) {
    let time = times[1]
    let mdy = times[0]
    mdy = mdy.split('/')
    let month = parseInt(mdy[0]);
    let day = parseInt(mdy[1]);
    let year = parseInt(mdy[2])
    return year + '-' + month + '-' + day + ' ' + time
}
let time = new Date()
let nowTime = timestampToTime(time.toLocaleString('en-US', { hour12: false }).split(" "))
//2.随机字符串函数
var zifu=Math.random().toString(36).substring(2);
var PeapleName=nowTime+'-'+zifu


相关实践学习
MongoDB数据库入门
MongoDB数据库入门实验。
快速掌握 MongoDB 数据库
本课程主要讲解MongoDB数据库的基本知识,包括MongoDB数据库的安装、配置、服务的启动、数据的CRUD操作函数使用、MongoDB索引的使用(唯一索引、地理索引、过期索引、全文索引等)、MapReduce操作实现、用户管理、Java对MongoDB的操作支持(基于2.x驱动与3.x驱动的完全讲解)。 通过学习此课程,读者将具备MongoDB数据库的开发能力,并且能够使用MongoDB进行项目开发。 &nbsp; 相关的阿里云产品:云数据库 MongoDB版 云数据库MongoDB版支持ReplicaSet和Sharding两种部署架构,具备安全审计,时间点备份等多项企业能力。在互联网、物联网、游戏、金融等领域被广泛采用。 云数据库MongoDB版(ApsaraDB for MongoDB)完全兼容MongoDB协议,基于飞天分布式系统和高可靠存储引擎,提供多节点高可用架构、弹性扩容、容灾、备份回滚、性能优化等解决方案。 产品详情: https://www.aliyun.com/product/mongodb
目录
相关文章
|
9天前
|
存储 人工智能 NoSQL
MongoDB 和 AI 赋能行业应用:电信和媒体
在本系列的下一篇文章中,我们将讨论 MongoDB + AI 在零售行业的应用
|
9天前
|
NoSQL MongoDB 数据库
深入探究MongoDB的ObjectId:唯一性、顺序性与应用指南
深入探究MongoDB的ObjectId:唯一性、顺序性与应用指南
|
9天前
|
存储 NoSQL 数据处理
探索MongoDB:灵活、高性能的NoSQL数据库解决方案与应用实践
探索MongoDB:灵活、高性能的NoSQL数据库解决方案与应用实践
|
19天前
|
传感器 人工智能 供应链
MongoDB和AI 赋能行业应用:制造业和汽车行业
本系列重点介绍AI应用于不同行业的关键用例,涵盖制造业和汽车行业、金融服务、零售、电信和媒体、保险以及医疗保健行业
3045 0
|
1月前
|
人工智能 NoSQL atlas
Fireworks AI和MongoDB:依托您的数据,借助优质模型,助力您开发高速AI应用
我们欣然宣布MongoDB与 Fireworks AI 正携手合作让客户能够利用生成式人工智能 (AI)更快速、更高效、更安全地开展创新活动
2650 1
|
1月前
|
存储 NoSQL 物联网
【MongoDB 专栏】MongoDB 在物联网(IoT)领域的应用
【5月更文挑战第11天】MongoDB,一种灵活可扩展的非关系型数据库,在物联网(IoT)领域中大放异彩。应对海量设备产生的多样化数据,MongoDB的文档型数据结构适应性强,适合存储设备信息及传感器读数。其实时更新、强大查询语言、索引机制和扩展性(通过分片技术)满足物联网的高实时性、复杂查询和数据增长需求。尽管面临数据安全和管理挑战,MongoDB已广泛应用于智能家居、工业 IoT 和智能交通等领域,并有望随着物联网技术进步和与其他领域的融合,如人工智能、大数据,持续发展。未来,优化数据质量、提升并发处理能力将是关键,MongoDB将在物联网的智能未来中扮演重要角色。
【MongoDB 专栏】MongoDB 在物联网(IoT)领域的应用
|
1月前
|
存储 监控 NoSQL
【MongoDB 专栏】MongoDB 在实时数据分析中的应用
【5月更文挑战第11天】MongoDB,作为强大的非关系型数据库,擅长实时数据分析。其灵活数据模型适应多样化数据,分布式架构支持水平扩展,处理海量数据和高并发查询。应用于物联网、实时监控、金融交易分析及电商个性化推荐等领域。结合流处理技术和数据可视化工具,提升实时分析效能。然而,注意数据一致性和性能调优是应用关键。未来,MongoDB将持续发展,为企业实时数据分析带来更多可能性和机遇。
【MongoDB 专栏】MongoDB 在实时数据分析中的应用
|
1月前
|
缓存 监控 NoSQL
【MongoDB 专栏】MongoDB 的变更流(Change Streams)应用
【5月更文挑战第11天】MongoDB的变更流是实时监控数据库动态的机制,允许应用程序订阅并响应文档的插入、更新和删除事件。它提供实时性、灵活性和解耦性,适用于数据同步、实时通知、缓存更新等多种场景。然而,使用时需注意性能、错误处理和版本兼容性。随着技术发展,变更流将在构建智能实时系统中扮演更重要角色,为数据处理带来新机遇。
【MongoDB 专栏】MongoDB 的变更流(Change Streams)应用
|
1月前
|
存储 NoSQL 大数据
【MongoDB 专栏】MongoDB 在大数据场景下的应用
【5月更文挑战第11天】MongoDB,适用于大数据时代,以其灵活数据模型、高可扩展性和快速性能在大数据场景中脱颖而出。它处理海量、多类型数据,支持高并发,并在数据分析、日志处理、内容管理和物联网应用中广泛应用。电商和互联网公司的案例展示了其在扩展性和业务适应性上的优势,但同时也面临数据一致性、资源管理、数据安全和性能优化的挑战。
【MongoDB 专栏】MongoDB 在大数据场景下的应用
|
1月前
|
存储 NoSQL Go
【Go语言专栏】Go语言中的MongoDB操作与NoSQL应用
【4月更文挑战第30天】本文介绍了Go语言中操作MongoDB的方法和NoSQL应用的优势。MongoDB作为流行的NoSQL数据库,以其文档型数据模型、高性能和可扩展性被广泛应用。在Go语言中,通过mongo-go-driver库可轻松实现与MongoDB的连接及插入、查询、更新和删除等操作。MongoDB在NoSQL应用中的优点包括灵活的数据模型、高性能、高可用性和易于扩展,使其成为处理大规模数据和高并发场景的理想选择。