MongoDB简介
MongoDB是一个开源的、文档型的NoSQL数据库程序。MongoDB将数据存储在类似JSON的文档中,操作起来更灵活方便。NoSQL数据库中的文档(documents)对应于SQL数据库中的一行。将一组文档组合在一起称为集合(collections),它大致相当于关系数据库中的表。
除了作为一个NoSQL数据库,MongoDB还有一些自己的特性:
"color: #ff0000">连接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();
使用逻辑操作符
"htmlcode">
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/
删除文档
"htmlcode">
async function removeCourse(id){ // const result = await Course.deleteMany({ _id: id}); const course = await Course.findByIdAndRemove(id); console.log(course) }
总结
以上所述是小编给大家介绍的Node.js对MongoDB进行增删改查操作的实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对网站的支持!
如果你觉得本文对你有帮助,欢迎转载,烦请注明出处,谢谢!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
RTX 5090要首发 性能要翻倍!三星展示GDDR7显存
三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。
首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。
据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。
更新日志
- 《年度十大发烧唱片精选 唱片榜获奖作品 2CD》[WAV/分轨][1GB]
- 归龙潮三枚天灯碎片位置在哪 笼律鸟任务天灯图文位置
- 归龙潮新手开荒阵容怎么搭配 新手前期阵容养成攻略
- 归龙潮中浦城区福鼠位置在哪 中浦城区福鼠收集位置大全
- MatteoPasqualini-JohannSebastianBachItalienischesKonzertFranzsischeOuvertureVierDue
- 【雨果唱片】陈百强《梦里人LPCD45》2012[WAV+CUE]
- 王菲.1994-《迷路》美卡引进版[WAV+CUE]
- 老外遇到八戒裸体Bug 网友:我需要用它对付蜘蛛精
- 《黑神话》超强越化补丁:游戏里有文字的地都改了
- 玩家吐槽《黑神话:悟空》唐僧相貌:一脸衰样 没半点气质
- 群星.1994-烧得厉害VOL.2我不是一个人拙滚石】【WAV+CUE】
- 群星.1994-烧得厉害VOL.3风笑痴【滚石】【WAV+CUE】
- 群星.1995-烧得厉害VOL.4两个世界【滚石】【WAV+CUE】
- 归龙潮中浦城区宝箱位置收集大全 中浦区宝箱解密攻略
- 黑神话悟空上品幽灯鬼精魄获取方法一览|上品幽灯鬼精魄收集攻略