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 数据库
|
23天前
|
人工智能 NoSQL atlas
如何用MongoDB Atlas和大语言模型,高效构建企业级AI应用?
利用生成式 AI 强化应用程序为客户打造令人叹服、真正差异化的体验意味着将人工智能建立在事实的基础之上
1593 0
|
1月前
|
NoSQL 搜索推荐 算法
【MongoDB】MongoDB在推荐系统中的实践应用
【4月更文挑战第1天】【MongoDB】MongoDB在推荐系统中的实践应用
|
4月前
|
存储 NoSQL MongoDB
阿里云 Flink 原理分析与应用:深入探索 MongoDB Schema Inference
本文整理自阿里云 Flink 团队归源老师关于阿里云 Flink 原理分析与应用:深入探索 MongoDB Schema Inference 的研究。
46944 2
阿里云 Flink 原理分析与应用:深入探索 MongoDB Schema Inference
|
4月前
|
存储 NoSQL 大数据
MongoDB 在内容管理场景的应用
MongoDB 在内容管理场景的应用
111 0
|
10月前
|
存储 JSON NoSQL
NoSql非关系型数据库之MongoDB应用(三):MongoDB在项目中的初步应用
NoSql非关系型数据库之MongoDB应用(三):MongoDB在项目中的初步应用
|
5月前
|
人工智能 NoSQL atlas
MongoDB推出四项AI驱动的新功能,助力开发者提升效率并加速应用程序现代化
生成式人工智能让开发者有机会构建更好的应用程序。通过自动执行重复性任务,由AI驱动的工具和功能可以帮助开发者节省大量时间和精力,同时更快地交付更高质量的应用程序
MongoDB推出四项AI驱动的新功能,助力开发者提升效率并加速应用程序现代化
|
9月前
|
NoSQL API MongoDB
MongoDB高级应用之数据转存与恢复(5)
创建索引同时指定索引的名字
124 0
|
9月前
|
存储 NoSQL Java
|
9月前
|
存储 NoSQL JavaScript
MongoDB实例:构建一个简单的任务管理应用
MongoDB作为一种灵活的文档型数据库,适用于多种应用场景。在本文中,我们将使用MongoDB构建一个简单的任务管理应用,展示其在实际应用中的使用。
101 1