当前位置:网站首页>Mongoose模块
Mongoose模块
2022-07-30 16:43:00 【THER1881】
一、Mongoose
Mongoose是在node.js环境中对MongoDB数据库操作的封装,一种对象模型工具,可以将数据库中的数据转换为JavaScript对象供我们使用。
1、名词解释
Schema :
它是一种以文件形式存储的数据库模型骨架,不具备对数据库操作的能力,仅仅只是数据库在程序片段中的一种表现,可以理解为表结构。
Model :
由Schema发布生成的模型,具有抽象属性和行为的数据库操作对
Entity :
由Model创建的实体,他的操作也会影响数据库
2、Schema、Model、Entity的关系
Schema生成Model,Model创造Entity,Model和Entity都可对数据库操作造成影响,但Model比Entity更具操作性。
3、命名规范(建议)
var PersonSchema; //Person的文本属性
var PersonModel; //Person的数据库模型
var PersonEntity; //Person实体
4、实现增删改查
4.1、安装插件
npm install mongoose
4.2、引用:
var mongoose = require(‘mongoose’);
4.3、创建mongoconfig.js用于连接MongoDB数据库
// 导入mongoose模块
const mongoose = require('mongoose')
//定义连接mogondb的字符串(链接地址)
const db_url= 'mongodb://localhost:27017/mvc'
//连接
mongoose.connect(db_url,{
useNewUrlParser:true,useUnifiedTopology:true})
//连接成功
mongoose.connection.on('connected',function (){
console.log('MongoDB Connection open to'+db_url)
})
//连接异常
mongoose.connection.on('error',function (err){
console.log('MongoDB Connection Eroor:'+err)
})
//断开连接
mongoose.connection.on('disconnected',function (){
console.log('MongoDB disconnectied')
})
module.exports=mongoose
4.4、创建Shema(classes.js)
var mongoose = require('../mogoconfig')
var Schema = mongoose.Schema
//定义schema
var ClassesSchema = new Schema({
name:{
type:String},
age:{
type:Number},
sex:{
type:String},
hobby:{
type:Array}
});
//由Schema生成model,model具有对数据库的操作能力
module.exports = mongoose.model('Classes',ClassesSchema)
4.5、创建路由文件
4.6、增删改查
(1)、增加:使用Model的实例调用save方法(使用Entity操作数据库)
var express = require('express')
const ClassesModel = require('../config/model/classes')
const router = express.Router()
//http://localhost:3000/mongo/add
router.get('/add',(req, res) => {
let clazz = new ClassesModel({
name:'郭芙',
age:22,
sex:'女',
hobby:['武术','绘画']
})
clazz.save(function (err,result){
if(err){
res.json({
code:1001,
msg:'插入数据失败'
})
}else{
res.json({
code:1002,
msg:'插入数据成功',
data:result
})
}
})
})
module.exports = router

(2)、删除:使用Model操作数据库
a、deleteOne:删除一条记录,返回删除的数量
b、deleteMany:删除多条记录,返回删除的数量
c、findOneAndDelete:先查找后删除,若没有找到匹配的记录不执行删除,返回null
d、findByIdAndDelete
var express = require('express')
const ClassesModel = require('../config/model/classes')
const router = express.Router()
//http://localhost:3000/mongo/remove
router.delete('/remove',(req, res) => {
ClassesModel.deleteOne({
'name':'小红'},(err,result)=>{
if(err){
res.json({
code:1001,
msg:'删除失败'
})
}else{
res.json({
code:1002,
msg:'删除成功',
data:result
})
}
})
})
module.exports = router

删除后"小红"后的数据库:
(3)、更新:使用Model操作数据库
a、updateOne、updateMany:返回更新的数量
b、findOneAndUpdate、findByIdAndUpdate:先查找后更新,若没有找到匹配的记录不执行删除,返回null
var express = require('express')
const ClassesModel = require('../config/model/classes')
const router = express.Router()
//http://localhost:3000/mongo/modify
router.put('/modify',(req, res) => {
ClassesModel.updateOne({
'name':'小王'},{
'name':'王五','age':'28'},(err,result)=>{
if(err){
res.json({
code:1001,
msg:'更新失败'
})
}else{
res.json({
code:1002,
msg:'更新成功',
data:result
})
}
})
})
module.exports = router

更新后数据:
(4)、查询:使用Model操作数据库
a、find():查询所有
b、findOne({}):按条件查询
c、findById():按id查询
var express = require('express')
const ClassesModel = require('../config/model/classes')
const router = express.Router()
//http://localhost:3000/mongo/findAll
router.get('/findAll',(req, res) => {
ClassesModel.find(function(err,result){
if(err){
console.log(err)
res.send({
code:1001,
msg:'查询失败'
})
}else{
res.send({
code:1002,
msg:'查询成功',
data:result
})
}
})
})
module.exports = router

边栏推荐
- 华为云数据治理生产线DataArts,让“数据'慧'说话”
- MySQL 8.0.29 解压版安装教程(亲测有效)
- Public Key Retrieval is not allowed error solution
- Wuhan Star Sets Sail: Overseas warehouse infrastructure has become a major tool for cross-border e-commerce companies to go overseas
- Public Key Retrieval is not allowed报错解决方案
- Visual Studio 集成Qt开发环境的一些注意事项
- PyQt5快速开发与实战 9.2 数据库处理
- 2022-07-30 Androd 进入深度休眠后把WIFI给关掉,唤醒之后重新打开WIFI
- [TypeScript] Introduction, Development Environment Construction, Basic Types
- (一)云计算技术学习--虚拟化vSphere学习
猜你喜欢

登录模块调试-软件调试入门

数据库的三大范式

Public Key Retrieval is not allowed报错解决方案

DTSE Tech Talk丨第2期:1小时深度解读SaaS应用系统设计

【SOC】Classic output hello world

SocialFi 何以成就 Web3 去中心化社交未来

为什么中年男人爱出轨?
![[NCTF2019] Fake XML cookbook-1|XXE vulnerability|XXE information introduction](/img/29/92b9d52d17a203b8bdead3eb2c902e.png)
[NCTF2019] Fake XML cookbook-1|XXE vulnerability|XXE information introduction

PHP message feedback management system source code

PCIE下载的驱动安装
随机推荐
MySql统计函数COUNT详解
Nervegrowold d2l (7) kaggle housing forecast model, numerical stability and the initialization and activation function
新零售saas小程序如何探索数字化门店的破局之路?
How does the new retail saas applet explore the way to break the digital store?
Goland 开启文件保存自动进行格式化
游戏显示分辨率的逆向分析
探究CSAPP实验二-bomb lab-第一节
如何在分面中添加数学表达式标签?
No qualifying bean of type问题解决
PHP message feedback management system source code
华为云数据治理生产线DataArts,让“数据‘慧’说话”
CMake库搜索函数居然不搜索LD_LIBRARY_PATH
静态网页和动态网页的不同之处;该如何选择服务器呢
完美绕开CRC32检测的无痕hook
游戏窗口化的逆向分析
How to connect redis in node.js?
PCIE入门
(1) Cloud computing technology learning - virtualized vSphere learning
数据库的三大范式
win下搭建php环境的方法
