本篇文章為大家展示了使用Node.js怎么對MongoDB進行增刪改查操作,內容簡明扼要并且容易理解,絕對能使你眼前一亮,通過這篇文章的詳細介紹希望你能有所收獲。
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進行增刪改查操作,你們學到知識或技能了嗎?如果還想學到更多技能或者豐富自己的知識儲備,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。