Node.js对MongoDB进行增删改查操作的实例代码
- 作者: 我系隔壁地老王
- 来源: 51数据库
- 2021-08-10
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更新操作符,请参考:
删除文档
•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进行增删改查操作的实例代码,希望对大家有所帮助
