Node.js对MongoDB进行增删改查操作的实例代码

所属分类: 网络编程 / JavaScript 阅读数: 1179
收藏 0 赞 0 分享

MongoDB简介

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

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

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

连接MongoDB

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

const mongoose = require('mongoose');

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

Schema

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

Schema类型

const courseSchema = new mongoose.Schema({
  name: String,
  author: String,
  tags: [String],
  date: {type: Date, default: Date.now},
  isPublished: Boolean
});

Model

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

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

新增(保存)一个文档

async function createCourse(){
  const course = new Course({
    name: 'Nodejs Course',
    author: 'Hiram',
    tags: ['node', 'backend'],
    isPublished: true
  });
  
  const result = await course.save();
  console.log(result);
}

createCourse();

查找文档

async function getCourses(){
  const courses = await Course
    .find({author: 'Hiram', isPublished: true})
    .limit(10)
    .sort({name: 1})
    .select({name: 1, tags:1});
  console.log(courses);
}
getCourses();

使用比较操作符

比较操作符

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

使用逻辑操作符

•or (或) 只要满足任意条件
•and (与) 所有条件均需满足

async function getCourses(){
  const courses = await Course
    // .find({author: 'Hiram', isPublished: true})
    .find()
    // .or([{author: 'Hiram'}, {isPublished: true}])
    .and([{author: 'Hiram', isPublished: true}])
    .limit(10)
    .sort({name: 1})
    .select({name: 1, tags:1});
  console.log(courses);
}
getCourses();

使用正则表达式

async function getCourses(){
  const courses = await Course
    // .find({author: 'Hiram', isPublished: true})
    //author字段以“Hiram”开头
    // .find({author: /^Hiram/})
    //author字段以“Pierce”结尾
    // .find({author: /Pierce$/i })
    //author字段包含“Hiram”
    .find({author: /.*Hiram.*/i })
    .limit(10)
    .sort({name: 1})
    .select({name: 1, tags:1});
  console.log(courses);
}
getCourses();

使用count()计数

async function getCourses(){
  const courses = await Course
    .find({author: 'Hiram', isPublished: true})
    .count();
  console.log(courses);
}
getCourses();

使用分页技术

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

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

更新文档

先查找后更新

async function updateCourse(id){
  const course = await Course.findById(id);
  if(!course) return;
  course.isPublished = true;
  course.author = 'Another Author';
  const result = await course.save();
  console.log(result);
}

直接更新

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

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

删除文档

•deleteOne 删除一个
•deleteMany 删除多个
•findByIdAndRemove 根据ObjectID删除指定文档

async function removeCourse(id){
  // const result = await Course.deleteMany({ _id: id});
  const course = await Course.findByIdAndRemove(id);
  console.log(course)
}

总结

以上所述是小编给大家介绍的Node.js对MongoDB进行增删改查操作的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!

更多精彩内容其他人还在看

AngularJs IE Compatibility 兼容老版本IE

本文主要介绍AngularJs IE Compatibility 兼容老版本IE的问题及解决办法,有兴趣的小伙伴可以参考下
收藏 0 赞 0 分享

AngularJs Modules详解及示例代码

本文主要介绍AngularJs Modules的相关知识,这里整理了详细的资料及简单示例代码,有兴趣的朋友可以参考下
收藏 0 赞 0 分享

AngularJs Scope详解及示例代码

本文主要介绍AngularJs Scope的知识,这里整理了详细资料及示例代码,有兴趣的小伙伴可以参考下
收藏 0 赞 0 分享

node.js中module.exports与exports用法上的区别

Node.js 引入了模块(Module)概念,一个模块可以通过module.exports 或 exports 将函数、变量等导出,以使其它 JavaScript 脚本通过require() 函数引入并使用。那么node.js中module.exports与exports有什么
收藏 0 赞 0 分享

基于JS实现发送短信验证码后的倒计时功能(无视页面刷新,页面关闭不进行倒计时功能)

这篇文章主要介绍了基于JS实现发送短信验证码后的倒计时功能(无视页面刷新,页面关闭不进行倒计时功能)的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

基于jQuery实现发送短信验证码后的倒计时功能(无视页面关闭)

最近做了一个项目,其中有需求要求实现发送短信验证码后倒计时功能,其中有个难点:要求关闭页面也进行倒计时。好吧,下面小编把jquery 发送验证码倒计时的实现代码分享给大家,大家可以参考下
收藏 0 赞 0 分享

js绘制购物车抛物线动画

这篇文章主要为大家详细介绍了js绘制购物车抛物线动画,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

vue.js入门教程之绑定class和style样式

小编之前介绍了通过vue.js计算属性,不知道大家都学会了吗。那这篇文章中我们将一起学习vue.js实现绑定class和style样式,有需要的朋友们可以参考借鉴。
收藏 0 赞 0 分享

纯JS实现可拖拽表单的简单实例

下面小编就为大家带来一篇纯JS实现可拖拽表单的简单实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

js实现StringBuffer的简单实例

下面小编就为大家带来一篇js实现StringBuffer的简单实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享
查看更多