转:

MongoDB 在Node中的应用

文章目录

  • 一 、什么是 MongoDB?
  • 二、小Demo
  • 三、Demo 增删改查
    • 3.1 新增
    • 3.2 查询
      • 3.2.1 查询所有 [{},{}] 找不到返回 []
      • 3.2.2 按条件查询 [{}] 即使只有一条数据也会放到一个数组当中
      • 3.2.3 返回找到的第一个元素
    • 3.3 删除数据 有多少个删除多少个
    • 3.4 更新数据
      • 3.4.1 User.findByIdAndUpdate() 根据id来更新
    • 3.5 一览
  • 四、模块化
    • 4.1 介绍
    • 4.2、模块化解决方法
      • 2.1 App.js
      • 2.2 db.js
      • 2.3 user.js
      • 2.4 news.js
      • 2.5 关于性能问题

一 、什么是 MongoDB?

二、小Demo

提示需要先在官网下载,安装。
MongoDB官网下载

然后配置环境变量

之后如果能看到版本信息就没问题了。
mongod --version

const mongoose = require('mongoose');
// 连接数据库
mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useUnifiedTopology: true }); // 创建一个模型
// 就是在设计数据库
// MongoDB是动态的,非常灵活,只需要在代码中设计你的数据库就可以了
// mongoose 这个包就可以让你的设计编写过程变得非常的简单
// 模型名称在 mongoose中实际上是 小写复数 carts
const Cat = mongoose.model('Cat', { name: String }); for (let i = 0; i < 101; i++) {
// 实例化一个 Cat
const kitty = new Cat({ name: '我是' + i}); // 持久化保存 kitty实例
kitty.save().then(() => console.log('meow'));
}

效果:

三、Demo 增删改查

先创建一个基本的实例

const mongoose = require('mongoose')

// 1. 连接数据库 连接本机的are数据库
// 如果没有该数据库 则会自动创建,不过不是立马创建,而是当你插入第一条数据的时候创建
mongoose.connect('mongodb://localhost/are') // 2. 设计文档结构(表结构) Schema理解为架构 结构
// 字段名称就是表结构中的属性名称
// 约束的目的是保持数据的完整性 统一性
const userSchema = new mongoose.Schema({
username: {
type: String,
require: true,//必须有
},
password: {
type: String,
require: true
},
email: {
type: String
}
});
// 3. 将文档架构发布为模型
// mongoose.model 方法就是将一个架构发布为 model
// 第一参数:传入一个 大写名词单数字符串用 来表示数据库名称 User
// mongoose会自动将大写名称的字符串生成 小写复数 的集合名称 users
// 第二个参数: 架构 Schema
// 返回值:模型构造函数
const User = mongoose.model('User', userSchema); // 4.当我们有了模型构造函数,就可以对 User 集合中的数据为所欲为了

有关增删改查的相关API
MongoDB API

3.1 新增

const admin = new User({
username: 'zs',
password: '123456',
email: 'admin@admin.com'
})
// 持久化保存起来 返回值是刚刚插入的数据
admin.save().then(value => {
console.log("存储成功:",value);
}, reason => {
console.log('存储失败:',reason);
})

3.2 查询

3.2.1 查询所有 [{},{}] 找不到返回 []

User.find().then(value => {
console.log('查询结果:', value);
}, reason => {
console.log('查询失败:', reason);
})

3.2.2 按条件查询 [{}] 即使只有一条数据也会放到一个数组当中

找不到返回 []

User.find({
username: 'zs2134'
}).then(value => {
console.log('查询结果:', value);
}, reason => {
console.log('查询失败:', reason);
})

3.2.3 返回找到的第一个元素

返回值:对象 {} 只返回查询到的第一个数据
找不到返回 null

User.findOne({
username: 'zs',
password: '2'
}).then(value => {
console.log('查询结果:', value);
}, reason => {
console.log('查询失败:', reason);
})

3.3 删除数据 有多少个删除多少个

返回值 { n: 3, ok: 1, deletedCount: 3 }

User.remove({
username: 'admin'
}).then(result => {
console.log('删除成功', result);
}, err => {
console.log('删除失败', err);
})

3.4 更新数据

3.4.1 User.findByIdAndUpdate() 根据id来更新

new: true 表示返回的是更新后的数据,不写返回的是更新之前的数据

User.findByIdAndUpdate('5fd0756d944530385829b677', {
password: '000'
}, { new: true }).then(result => {
console.log('更新成功', result);
}, err => {
console.log('更新失败', err);
})

3.5 一览

原文件

// 1.引入 mongoose
const mongoose = require('mongoose') // 2.建立连接
mongoose.connect('mongodb://127.0.0.1:27017/eggcms', { useNewUrlParser: true, useUnifiedTopology: true }) // 3.操作users表(集合) 定义一个 Schema
let UserSchme = mongoose.Schema({
name: String,
age: Number,
status: Number
}) // 4.定义数据库模型 操作数据库
// model里面的第一个参数 要注意:1.首字母大写 2.要和集合名称对应(数据库表名)
// 第三个参数指定连接的集合名称 小写没有复数
let User = mongoose.model('User', UserSchme, 'user') // 5.查询数据 // User.find({}).then(res => {
// console.log('res:', res);
// }, err => {
// console.log('err:', err);
// }) // 定义一个新的 Schema
let NewsSchema = mongoose.Schema({
title: 'string',
author: String,
pic: String,
content: String,
status: Number
}) // 定义操作数据库的 Model
let News = mongoose.model('News', NewsSchema, 'news') // 增加数据
// let news = new News({
// title: '我是新闻标题2',
// author: "我是作者2",
// pic: "images2",
// content: "hhh2",
// status: 1
// })
// news.save().then(res => {
// //返回值是新增的数据
// console.log('res:', res);
// }, err => {
// console.log('err:', err);
// }) // 修改数据
// News.updateOne({
// "_id": "5fd2ee9f29c50109b0e2e828"
// }, {
// content: "哈哈哈"
// }).then(res => {
// // { n: 1, nModified: 1, ok: 1 }
// console.log('res:', res);
// }, err => {
// console.log('err:', err);
// }) // 删除数据
News.deleteOne({ "_id": "5fd2f086969fdb0680ac9fd6" }).then(res => {
// { n: 1, ok: 1, deletedCount: 1 }
console.log('res:', res);
}, err => {
console.log('err:', err);
})

四、模块化

4.1 介绍

在使用 mongosee 操作 mongodb 数据库时,要准备4个比较繁琐的过程,分别是

// 第一步:引入模块
const mongoose = require('mongoose') // 第二步:建立连接
mongoose.connect('mongodb://127.0.0.1:27017/eggcms', { useNewUrlParser: true, useUnifiedTopology: true }) // 第三步:定义 Schema
const UserSchme = mongoose.Schema({
name: String,
age: Number,
status: {
type: Number,
default: 1
}
}) //第四步:定义数据库模型
const UserModel = mongoose.model('User', UserSchme, 'user')

当我们在实际开发项目中,如果要操作多个集合(表)的话,结构就会变得非常的混乱,那么怎样解决这个问题呢?

这个时候 模块化就登场了。

4.2、模块化解决方法

目录结构

├─App.js
├─model
| ├─db.js
| ├─news.js
| └─user.js

2.1 App.js

const UserModel = require('./model/user')
const NewsModel = require('./model/news') // 查找所有数据
// UserModel.find({}).then(res => {
// console.log(res);
// }, err => {
// console.log(err);
// }) const addNews = new NewsModel({
title: '测试1',
content: 20
}) addNews.save().then(res => {
NewsModel.find({}).then(res => {
console.log(res);
}, err => {
console.log(err);
})
}, err => {
console.log('增加数据失败:', err);
})

2.2 db.js

// 连接数据库

// 1.引入
const mongoose = require('mongoose') // 2.连接
mongoose.connect('mongodb://127.0.0.1:27017/eggcms', { useNewUrlParser: true, useUnifiedTopology: true }).then(res => {
console.log("连接成功");
}, err => {
console.log("连接失败:", err);
}) module.exports = mongoose

2.3 user.js

let mongoose = require('./db')

// 配置 schema 和数据模型
const UserSchema = mongoose.Schema({
name: String,
age: Number,
status: {
type: Number,
default: 1
}
}) // const UserModel = mongoose.model('User', UserSchema, 'user')
// module.exports = UserModel // 简写
module.exports = mongoose.model('User', UserSchema, 'user')

2.4 news.js

let mongoose = require('./db')

// 配置 schema 和数据模型
const NewsSchema = mongoose.Schema({
title: 'string',
author: String,
pic: String,
content: String,
status: {
type: Number,
default: 1
}
}) module.exports = mongoose.model('News', NewsSchema, 'news')

2.5 关于性能问题

你可能已经注意到了,我们在 user.jsnews.js 都引入了 db.js, 那么会不会造成资源浪费或性能降低的问题呢?

答案是不会的,这里实践看一下:

App.js

console.time('user')
const UserModel = require('./model/user')
console.timeEnd('user'); console.time('news')
const NewsModel = require('./model/news')
console.timeEnd('news');

output:

user: 303.144ms
news: 1.35ms

可以非常直观的看到 news.js里边第二次引入的 db.js 并没有照成资源浪费,因为 mongoose 底层做出了相应的处理。

好了,本文就到这里,如果对你有帮助的话,亲,还请点个赞哦(会回赞的),

转:

MongoDB 在Node中的应用

MongoDB 在Node中的应用的更多相关文章

  1. 在node中使用MongoDB

    1.下载安装包,进行安装: https://www.mongodb.com/download-center/community 参考网址:https://www.cnblogs.com/ymwange ...

  2. Node中使用MongoDB

    简介 MongoDB 中文文档 MongoDB是一个介于关系数据库和非关系数据库(nosql)之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的. Mongoose 在Node中可以使用 Mo ...

  3. Node中的定时器详解

    在大多数的业务中,我们都会有一些需求,例如几秒钟实现网页的跳转,几分钟对于后台数据进行清理,node与javascript都具有将代码延迟一段时间的能力.在node中可以使用三种方式实现定时功能:超时 ...

  4. MongoDB Native Node.js Driver

    写在前面 最近读<node.js学习指南>,对于mongodb没有介绍太多的工作原理,但是对于一个前端开发者,即使你还没有用过这种数据库也可以让你很好的理解和使用       一本非常好的 ...

  5. mongodb原生node驱动

    写在前面 最近读<node.js学习指南>,对于mongodb没有介绍太多的工作原理,但是对于一个前端开发者,即使你还没有用过这种数据库也可以让你很好的理解和使用       一本非常好的 ...

  6. node 进阶 | 通过node中如何捕获异常阐述express的特点

    node如何捕获异常 node基于js的单线程,有了非阻塞异步回调的概念,但是在处理多个并发连接时,并发环境要求高,最重要的是单线程,单核CPU,一个进程crash则web服务都crash,但是为什么 ...

  7. node中的Stream-Readable和Writeable解读

    在node中,只要涉及到文件IO的场景一般都会涉及到一个类-Stream.Stream是对IO设备的抽象表示,其在JAVA中也有涉及,主要体现在四个类-InputStream.Reader.Outpu ...

  8. 深入理解jQuery、Angular、node中的Promise

    最初遇到Promise是在jQuery中,在jQuery1.5版本中引入了Deferred Object,这个异步队列模块用于实现异步任务和回调函数的解耦.为ajax模块.队列模块.ready事件提供 ...

  9. (转载)MongoDB C#驱动中Query几个方法

    MongoDB C#驱动中Query几个方法 Query.All("name", "a", "b");//通过多个元素来匹配数组 Query ...

随机推荐

  1. 2020Nowcode多校 Round9 B.Groundhog and Apple Tree

    题意 给一棵树 初始\(hp=0\) 经过一条边会掉血\(w_{i}\) 第一次到达一个点可以回血\(a_{i}\) 在一个点休息\(1s\)可以回复\(1hp\) 血不能小于\(0\) 每条边最多经 ...

  2. Codeforces Round #642 (Div. 3)

    比赛链接:https://codeforces.com/contest/1353 A - Most Unstable Array 题意 构造大小为 $n$,和为 $m$ 的非负数组 $a$,使得相邻元 ...

  3. hdu 1517 Multiplication Game

    题意: 用整数p乘以2到9中的一个数字.斯坦总是从p = 1开始,做乘法,然后奥利乘以这个数,然后斯坦,以此类推.游戏开始前,他们画一个整数1 < n < 4294967295,谁先到达p ...

  4. Codeforces Round #645 (Div. 2) D. The Best Vacation (贪心,二分)

    题意:一年有\(n\)个月,每月有\(d_{i}\)天,找出连续的\(x\)天,使得这\(x\)天的日期总和最大,任意一年都能选. 题解:首先要先贪心,得到:连续的\(x\)天的最后一天一定是某个月的 ...

  5. Codeforces Global Round 9 C. Element Extermination (思维,栈)

    题意:有一个长度\(n\)的序列,如果\(a_{i}<a_{i+1}\),那么可以选择删除\(a_{i}\)或者\(a_{i+1}\),再继续操作,问是否能够将序列删到只剩一个元素. 题解:感觉 ...

  6. Python内置模块(你还在pip install time?)&& apt-get install -f

    一.内置模块 之前不知道time是python自带的,还用pip安装.......还报错..... Python中有以下模块不用单独安装 1.random模块 2.sys模块 3.time模块 4.o ...

  7. M1 MacBook安装Homebrew

    在装载M1芯片的MacBook产品上,默认是不带有homebrew这款包管理工具的,具体原因官方解释为适配问题,原有的homebrew无法与silicon Mac机型匹配.但是这并不意味着我们不可以在 ...

  8. MySQL 回表查询 & 索引覆盖优化

    回表查询 先通过普通索引的值定位聚簇索引值,再通过聚簇索引的值定位行记录数据 建表示例 mysql> create table user( -> id int(10) auto_incre ...

  9. Gym102361A Angle Beats(直角三角形 计算几何)题解

    题意: \(n\)个点,\(q\)个询问,每次问包含询问点的直角三角形有几个 思路: 代码: #include<bits/stdc++.h> using namespace std; co ...

  10. js & array remove one item ways

    js & array remove one item ways // array remove one item ways let keys = [1,2,3,4,5,6,7]; let ke ...