转:

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. hdu2430Beans(单调队列)

     Mr. Pote's shop sells beans now. He has N bags of beans in his warehouse, and he has numbered them ...

  2. 连接MongoDb数据库 -- Python

    1.安装完mongoDb数据库后,如果需要我们的Python程序和MongoDb数据库进行交互,需要安装pymongo模块: 安装方式:采用pip install pymongo的方式 Microso ...

  3. printf,sprintf,fprintf的区别与联系

    在写代码过程中总会遇到printf和sprintf,既然这两个都遇到了,那么不妨再加一个fprintf吧. 他们三个都是将格式化字符串输出,区别就是他们输出的目标不一样. (1).printf,是把格 ...

  4. git merge bug

    git merge bug 本地分支 dev commit 后, 直接 pull 远程 dev 分支, 导致远程 dev 分支 merge 到本地 dev 分支了, 取消本次 merge 操作? Re ...

  5. css scroll text without wrap & webkit-scrollbar

    css scroll text without wrap hidden webkit-scrollbar .tabs-title-box::-webkit-scrollbar, .tabs-conte ...

  6. React Native & Security

    React Native & Security https://reactnative.dev/docs/security React Native blogs https://reactna ...

  7. no need jQuery anymore & You don't need jQuery anymore!

    no need jQuery anymore & You don't need jQuery anymore! "use strict"; /** * * @author ...

  8. js useful skills blogs

    js useful skills blogs blogs https://davidwalsh.name/tutorials/javascript https://www.ruanyifeng.com ...

  9. VIM 官方教程

    VIM 官方教程 zh-hans vim official documents https://www.vim.org/docs.php https://vimhelp.org/ translatio ...

  10. React useMemo

    React useMemo react hooks https://reactjs.org/docs/hooks-reference.html#usememo useCallback & us ...