当前位置:网站首页>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

边栏推荐
- 第5章 SQL高级处理
- C语言学习之旅 【函数(二)】
- [NCTF2019] Fake XML cookbook-1|XXE vulnerability|XXE information introduction
- Qt 容器控件之Tab Widget 使用详解
- Security business revenue growth rate exceeds 70% 360 builds digital security leader
- .NET 6.0中使用Identity框架实现JWT身份认证与授权
- vivo宣布延长产品保修期限 系统上线多种功能服务
- 大厂面试官眼中的好简历到底长啥样
- Leetcode 118. Yanghui Triangle
- 深度学习区分不同种类的图片
猜你喜欢

You are a first-class loser, you become a first-class winner

【Linux操作系统】 虚拟文件系统 | 文件缓存

.NET 6.0中使用Identity框架实现JWT身份认证与授权

How to remove first character from php string

Navisworks切换语言

华为云数据治理生产线DataArts,让“数据‘慧’说话”

Goland 开启文件保存自动进行格式化

PHP留言反馈管理系统源码

Visual Studio编辑器 2019:scanf函数返回值被忽略(C4996)报错及解决办法

3D激光SLAM:LeGO-LOAM论文解读---激光雷达里程计与建图
随机推荐
静态网页和动态网页的不同之处;该如何选择服务器呢
DTSE Tech Talk丨Phase 2: 1 hour in-depth interpretation of SaaS application system design
Minio 入门
[AGC] Quality Service 2 - Performance Management Example
京东获取推荐商品列表 API
Visual Studio编辑器 2019:scanf函数返回值被忽略(C4996)报错及解决办法
武汉星起航跨境电商有前景吗?亚马逊的未来趋势如何发展?
Gvim order record
Rounding out the most practical way of several DLL injection
js 切换数据源的时候该缓存checkbox选中结果并回显?
Go新项目-编译热加载使用和对比,让开发更自由(3)
第六章:决胜秋招
Goland 开启文件保存自动进行格式化
Leetcode 118. 杨辉三角
3D激光SLAM:LeGO-LOAM论文解读---激光雷达里程计与建图
.NET 6.0中使用Identity框架实现JWT身份认证与授权
云厂商做生态需要“真连接、真赋能”,用“技术+真金实银”发展伙伴
游戏窗口化的逆向分析
Nervegrowold d2l (7) kaggle housing forecast model, numerical stability and the initialization and activation function
The way of life, share with you!
