经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » MongoDB » 查看文章
Node.js对MongoDB进行增删改查操作
来源:cnblogs  作者:皮蛋哥  时间:2019/4/18 8:38:05  对本文有异议

MongoDB简介

MongoDB是一个开源的、文档型的NoSQL数据库程序。MongoDB将数据存储在类似JSON的文档中,操作起来更灵活方便。NoSQL数据库中的文档(documents)对应于SQL数据库中的一行。将一组文档组合在一起称为集合(collections),它大致相当于关系数据库中的表。

除了作为一个NoSQL数据库,MongoDB还有一些自己的特性:

  • 易于安装和设置
  • 使用BSON(类似于JSON的格式)来存储数据
  • 将文档对象映射到应用程序代码很容易
  • 具有高度可伸缩性和可用性,并支持开箱即用,无需事先定义结构
  • 支持MapReduce操作,将大量数据压缩为有用的聚合结果
  • 免费且开源
  • ......

连接MongoDB

在Node.js中,通常使用Mongoose库对MongoDB进行操作。Mongoose是一个MongoDB对象建模工具,设计用于在异步环境中工作。

  1. const mongoose = require('mongoose');
  2. mongoose.connect('mongodb://localhost/playground')
  3. .then(() => console.log('Connected to MongoDB...'))
  4. .catch( err => console.error('Could not connect to MongoDB... ', err));

Schema

Mongoose中的一切都始于一个模式。每个模式都映射到一个MongoDB集合,并定义该集合中文档的形状。
Schema类型

  1. const courseSchema = new mongoose.Schema({
  2. name: String,
  3. author: String,
  4. tags: [String],
  5. date: {type: Date, default: Date.now},
  6. isPublished: Boolean
  7. });

Model

模型是根据模式定义编译的构造函数,模型的实例称为文档,模型负责从底层MongoDB数据库创建和读取文档。

  1. const Course = mongoose.model('Course', courseSchema);
  2. const course = new Course({
  3. name: 'Nodejs Course',
  4. author: 'Hiram',
  5. tags: ['node', 'backend'],
  6. isPublished: true
  7. });

新增(保存)一个文档

  1. async function createCourse(){
  2. const course = new Course({
  3. name: 'Nodejs Course',
  4. author: 'Hiram',
  5. tags: ['node', 'backend'],
  6. isPublished: true
  7. });
  8. const result = await course.save();
  9. console.log(result);
  10. }
  11. createCourse();

查找文档

  1. async function getCourses(){
  2. const courses = await Course
  3. .find({author: 'Hiram', isPublished: true})
  4. .limit(10)
  5. .sort({name: 1})
  6. .select({name: 1, tags:1});
  7. console.log(courses);
  8. }
  9. getCourses();

使用比较操作符

比较操作符

  1. async function getCourses(){
  2. const courses = await Course
  3. // .find({author: 'Hiram', isPublished: true})
  4. // .find({ price: {$gt: 10, $lte: 20} })
  5. .find({price: {$in: [10, 15, 20]} })
  6. .limit(10)
  7. .sort({name: 1})
  8. .select({name: 1, tags:1});
  9. console.log(courses);
  10. }
  11. getCourses();

使用逻辑操作符

  • or (或) 只要满足任意条件
  • and (与) 所有条件均需满足
  1. async function getCourses(){
  2. const courses = await Course
  3. // .find({author: 'Hiram', isPublished: true})
  4. .find()
  5. // .or([{author: 'Hiram'}, {isPublished: true}])
  6. .and([{author: 'Hiram', isPublished: true}])
  7. .limit(10)
  8. .sort({name: 1})
  9. .select({name: 1, tags:1});
  10. console.log(courses);
  11. }
  12. getCourses();

使用正则表达式

  1. async function getCourses(){
  2. const courses = await Course
  3. // .find({author: 'Hiram', isPublished: true})
  4. //author字段以“Hiram”开头
  5. // .find({author: /^Hiram/})
  6. //author字段以“Pierce”结尾
  7. // .find({author: /Pierce$/i })
  8. //author字段包含“Hiram”
  9. .find({author: /.*Hiram.*/i })
  10. .limit(10)
  11. .sort({name: 1})
  12. .select({name: 1, tags:1});
  13. console.log(courses);
  14. }
  15. getCourses();

使用count()计数

  1. async function getCourses(){
  2. const courses = await Course
  3. .find({author: 'Hiram', isPublished: true})
  4. .count();
  5. console.log(courses);
  6. }
  7. getCourses();

使用分页技术

通过结合使用 skip()limit() 可以做到分页查询的效果

  1. async function getCourses(){
  2. const pageNumber = 2;
  3. const pageSize = 10;
  4. const courses = await Course
  5. .find({author: 'Hiram', isPublished: true})
  6. .skip((pageNumber - 1) * pageSize)
  7. .limit(pageSize)
  8. .sort({name: 1})
  9. .select({name: 1, tags: 1});
  10. console.log(courses);
  11. }
  12. getCourses();

更新文档

先查找后更新

  1. async function updateCourse(id){
  2. const course = await Course.findById(id);
  3. if(!course) return;
  4. course.isPublished = true;
  5. course.author = 'Another Author';
  6. const result = await course.save();
  7. console.log(result);
  8. }

直接更新

  1. async function updateCourse(id){
  2. const course = await Course.findByIdAndUpdate(id, {
  3. $set: {
  4. author: 'Jack',
  5. isPublished: false
  6. }
  7. }, {new: true}); //true返回修改后的文档,false返回修改前的文档
  8. console.log(course);
  9. }

MongoDB更新操作符,请参考:https://docs.mongodb.com/manual/reference/operator/update/

删除文档

  • deleteOne 删除一个
  • deleteMany 删除多个
  • findByIdAndRemove 根据ObjectID删除指定文档
  1. async function removeCourse(id){
  2. // const result = await Course.deleteMany({ _id: id});
  3. const course = await Course.findByIdAndRemove(id);
  4. console.log(course)
  5. }

原文链接:http://www.cnblogs.com/hiramP/p/10724945.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号