当前位置:网站首页>Mongoose module
Mongoose module
2022-07-30 17:00:00 【THER1881】
一、Mongoose
Mongoose是在node.js环境中对MongoDB数据库操作的封装,一种对象模型工具,可以将数据库中的数据转换为JavaScript对象供我们使用.
1、名词解释
Schema :
它是一种以文件形式存储的数据库模型骨架,不具备对数据库操作的能力,Only the database performance in fragments of a,Can be understood as a table structure.
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,modelHas the ability to the operation of the database
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

边栏推荐
- Minio 入门
- Nervegrowold d2l (7) kaggle housing forecast model, numerical stability and the initialization and activation function
- Various meanings of SQL's PARTITION BY syntax (with examples)
- LeetCode318: Maximum product of word lengths
- 理解实现搜索二叉树
- Dive deep on Netflix‘s recommender system(Netflix推荐系统是如何实现的?)
- @Bean注解详解
- 23. Please talk about the difference between IO synchronization, asynchronous, blocking and non-blocking
- onenote使用
- 优酷视频元素内容召回系统:多级多模态引擎探索
猜你喜欢

Leetcode 118. Yanghui Triangle
![[TypeScript] Introduction, Development Environment Construction, Basic Types](/img/d7/b3175ab538906ac1b658a9f361ba44.png)
[TypeScript] Introduction, Development Environment Construction, Basic Types

数据库的三大范式

Nervegrowold d2l (7) kaggle housing forecast model, numerical stability and the initialization and activation function

FP6606ACAW4 TQFN-20L (3mmx3mm) USB双端口充电控制器 百盛电子代理

leetcode:1488. 避免洪水泛滥【二分 + 贪心】

【SOC】Classic output hello world

HUAWEI CLOUD data governance production line DataArts, let "data 'wisdom' speak"

【Linux Operating System】 Virtual File System | File Cache

Navisworks切换语言
随机推荐
MySql统计函数COUNT详解
Invalid or corrupt jarfile xxx.jar
服务器装好系统的电脑怎么分区
升级Win11后不喜欢怎么退回Win10系统?
@Bean注解详解
DTSE Tech Talk丨第2期:1小时深度解读SaaS应用系统设计
理解实现搜索二叉树
如何写一份高可读性的软件工程设计文档
华为云数据治理生产线DataArts,让“数据‘慧’说话”
.NET 6.0中使用Identity框架实现JWT身份认证与授权
How does the new retail saas applet explore the way to break the digital store?
论文阅读 (63):Get To The Point: Summarization with Pointer-Generator Networks
You are a first-class loser, you become a first-class winner
Login Module Debugging - Getting Started with Software Debugging
SLIM: Sparse Linear Methods (TopN推荐)
Mysql进阶优化篇01——四万字详解数据库性能分析工具(深入、全面、详细,收藏备用)
LeetCode318: Maximum product of word lengths
Discuz magazine/news report template (jeavi_line) UTF8-GBK template
Tensorflow中实现正则化
3D激光SLAM:LeGO-LOAM论文解读---系统概述部分
