Node.js對(duì)MongoDB進(jìn)行增刪改查操作的實(shí)例代碼
MongoDB簡(jiǎn)介
MongoDB是一個(gè)開源的、文檔型的NoSQL數(shù)據(jù)庫程序。MongoDB將數(shù)據(jù)存儲(chǔ)在類似JSON的文檔中,操作起來更靈活方便。NoSQL數(shù)據(jù)庫中的文檔(documents)對(duì)應(yīng)于SQL數(shù)據(jù)庫中的一行。將一組文檔組合在一起稱為集合(collections),它大致相當(dāng)于關(guān)系數(shù)據(jù)庫中的表。
除了作為一個(gè)NoSQL數(shù)據(jù)庫,MongoDB還有一些自己的特性:
•易于安裝和設(shè)置
•使用BSON(類似于JSON的格式)來存儲(chǔ)數(shù)據(jù)
•將文檔對(duì)象映射到應(yīng)用程序代碼很容易
•具有高度可伸縮性和可用性,并支持開箱即用,無需事先定義結(jié)構(gòu)
•支持MapReduce操作,將大量數(shù)據(jù)壓縮為有用的聚合結(jié)果
•免費(fèi)且開源
•......
連接MongoDB
在Node.js中,通常使用Mongoose庫對(duì)MongoDB進(jìn)行操作。Mongoose是一個(gè)MongoDB對(duì)象建模工具,設(shè)計(jì)用于在異步環(huán)境中工作。
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中的一切都始于一個(gè)模式。每個(gè)模式都映射到一個(gè)MongoDB集合,并定義該集合中文檔的形狀。
Schema類型
const courseSchema = new mongoose.Schema({
name: String,
author: String,
tags: [String],
date: {type: Date, default: Date.now},
isPublished: Boolean
});
Model
模型是根據(jù)模式定義編譯的構(gòu)造函數(shù),模型的實(shí)例稱為文檔,模型負(fù)責(zé)從底層MongoDB數(shù)據(jù)庫創(chuàng)建和讀取文檔。
const Course = mongoose.model('Course', courseSchema);
const course = new Course({
name: 'Nodejs Course',
author: 'Hiram',
tags: ['node', 'backend'],
isPublished: true
});
新增(保存)一個(gè)文檔
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();
使用正則表達(dá)式
async function getCourses(){
const courses = await Course
// .find({author: 'Hiram', isPublished: true})
//author字段以“Hiram”開頭
// .find({author: /^Hiram/})
//author字段以“Pierce”結(jié)尾
// .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()計(jì)數(shù)
async function getCourses(){
const courses = await Course
.find({author: 'Hiram', isPublished: true})
.count();
console.log(courses);
}
getCourses();
使用分頁技術(shù)
通過結(jié)合使用 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更新操作符,請(qǐng)參考:https://docs.mongodb.com/manual/reference/operator/update/
刪除文檔
•deleteOne 刪除一個(gè)
•deleteMany 刪除多個(gè)
•findByIdAndRemove 根據(jù)ObjectID刪除指定文檔
async function removeCourse(id){
// const result = await Course.deleteMany({ _id: id});
const course = await Course.findByIdAndRemove(id);
console.log(course)
}
總結(jié)
以上所述是小編給大家介紹的Node.js對(duì)MongoDB進(jìn)行增刪改查操作的實(shí)例代碼,希望對(duì)大家有所幫助,如果大家有任何疑問請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!
如果你覺得本文對(duì)你有幫助,歡迎轉(zhuǎn)載,煩請(qǐng)注明出處,謝謝!
- express使用Mongoose連接MongoDB操作示例【附源碼下載】
- Node+Express+MongoDB實(shí)現(xiàn)登錄注冊(cè)功能實(shí)例
- 零基礎(chǔ)搭建Node.js、Express、Ejs、Mongodb服務(wù)器及應(yīng)用開發(fā)入門
- vue+socket.io+express+mongodb 實(shí)現(xiàn)簡(jiǎn)易多房間在線群聊示例
- express+vue+mongodb+session 實(shí)現(xiàn)注冊(cè)登錄功能
- 如何優(yōu)雅的在一臺(tái)vps(云主機(jī))上面部署vue+mongodb+express項(xiàng)目
- webpack4+express+mongodb+vue實(shí)現(xiàn)增刪改查的示例
- nodejs連接mongodb數(shù)據(jù)庫實(shí)現(xiàn)增刪改查
- Java連接MongoDB進(jìn)行增刪改查的操作
- mongodb增刪改查詳解_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
- MongoDB簡(jiǎn)單操作示例【連接、增刪改查等】
- express+mongoose實(shí)現(xiàn)對(duì)mongodb增刪改查操作詳解
相關(guān)文章
Nodejs?Socket連接池及TCP?HTTP網(wǎng)絡(luò)模型詳解
這篇文章主要為大家介紹了Nodejs?Socket連接池及TCP?HTTP網(wǎng)絡(luò)模型,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08
nvm版本導(dǎo)致npm?install報(bào)錯(cuò)Unexpected?token?'.'的解決辦法
最近做項(xiàng)目遇到npm install 的問題,下面這篇文章主要給大家介紹了關(guān)于nvm版本導(dǎo)致npm?install報(bào)錯(cuò)Unexpected?token?'.'的解決辦法,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2022-07-07
安裝nvm并使用nvm安裝nodejs及配置環(huán)境變量的全過程
有時(shí)候使用nvm管理node會(huì)發(fā)現(xiàn)無法使用node或npm,主要原因是環(huán)境變量沒有配置成功,下面這篇文章主要給大家介紹了關(guān)于安裝nvm并使用nvm安裝nodejs及配置環(huán)境變量的相關(guān)資料,需要的朋友可以參考下2023-03-03
nodejs更新package.json中的dependencies依賴到最新版本的方法
今天小編就為大家分享一篇nodejs更新package.json中的dependencies依賴到最新版本的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2018-10-10
Node.js中console.log()輸出彩色字體的方法示例
這篇文章主要給大家介紹了關(guān)于Node.js中console.log()輸出彩色字體的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Node.js具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2019-12-12
Node.js版本發(fā)布策略頻率與穩(wěn)定性的平衡
這篇文章主要為大家介紹了Node.js版本發(fā)布策略頻率與穩(wěn)定性的平衡,幫助大家大家更清晰了解node發(fā)展史,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10

