欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Node.js對MongoDB進行增刪改查操作的實例代碼

 更新時間:2019年04月18日 10:11:51   作者:皮蛋哥  
這篇文章主要介紹了Node.js對MongoDB進行增刪改查操作 ,需要的朋友可以參考下

MongoDB簡介

MongoDB是一個開源的、文檔型的NoSQL數(shù)據(jù)庫程序。MongoDB將數(shù)據(jù)存儲在類似JSON的文檔中,操作起來更靈活方便。NoSQL數(shù)據(jù)庫中的文檔(documents)對應(yīng)于SQL數(shù)據(jù)庫中的一行。將一組文檔組合在一起稱為集合(collections),它大致相當于關(guān)系數(shù)據(jù)庫中的表。

除了作為一個NoSQL數(shù)據(jù)庫,MongoDB還有一些自己的特性:

•易于安裝和設(shè)置
•使用BSON(類似于JSON的格式)來存儲數(shù)據(jù)
•將文檔對象映射到應(yīng)用程序代碼很容易
•具有高度可伸縮性和可用性,并支持開箱即用,無需事先定義結(jié)構(gòu)
•支持MapReduce操作,將大量數(shù)據(jù)壓縮為有用的聚合結(jié)果
•免費且開源
•......

連接MongoDB

在Node.js中,通常使用Mongoose庫對MongoDB進行操作。Mongoose是一個MongoDB對象建模工具,設(shè)計用于在異步環(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中的一切都始于一個模式。每個模式都映射到一個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ù),模型的實例稱為文檔,模型負責從底層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
});

新增(保存)一個文檔

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”結(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()計數(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更新操作符,請參考:https://docs.mongodb.com/manual/reference/operator/update/

刪除文檔

•deleteOne 刪除一個
•deleteMany 刪除多個
•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對MongoDB進行增刪改查操作的實例代碼,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!

相關(guān)文章

  • nodeJS實現(xiàn)路由功能實例代碼

    nodeJS實現(xiàn)路由功能實例代碼

    本篇文章主要介紹了nodeJS實現(xiàn)路由功能實例代碼,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-06-06
  • 淺談NodeJs之數(shù)據(jù)庫異常處理

    淺談NodeJs之數(shù)據(jù)庫異常處理

    這篇文章主要介紹了淺談NodeJs之數(shù)據(jù)庫異常處理,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-10-10
  • Node版本升級和降級之node版本管理工具nvm詳解

    Node版本升級和降級之node版本管理工具nvm詳解

    nvm是管理node版本的工具,一個電腦中可以安裝多個node版本,當我們想使用哪個版本就切換成哪個版本,而nvm則是提供切換node版本的工具,這篇文章主要給大家介紹了關(guān)于Node版本升級和降級之node版本管理工具nvm的相關(guān)資料,需要的朋友可以參考下
    2022-08-08
  • Nodejs 搭建簡單的Web服務(wù)器詳解及實例

    Nodejs 搭建簡單的Web服務(wù)器詳解及實例

    這篇文章主要介紹了Nodejs 搭建簡單的Web服務(wù)器詳解及實例的相關(guān)資料,并附實例代碼和實現(xiàn)效果圖,需要的朋友可以參考下
    2016-11-11
  • 詳解Node.js如何處理ES6模塊

    詳解Node.js如何處理ES6模塊

    學習JavaScript語言,你會發(fā)現(xiàn)它有兩種格式的模塊。一種是ES6模塊,簡稱ESM;另一種是Node.js專用的CommonJS模塊,簡稱 CJS。這兩種模塊不兼容。很多人使用Node.js,只會用require()加載模塊,遇到ES6模塊就不知道該怎么辦。本文就來談?wù)凟S6模塊在Node.js里面怎么使用。
    2021-05-05
  • nodejs?express路由匹配控制及Router模塊化使用詳解

    nodejs?express路由匹配控制及Router模塊化使用詳解

    這篇文章主要為大家介紹了nodejs?express路由匹配控制及Router模塊化使用示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-10-10
  • node.js中的事件處理機制詳解

    node.js中的事件處理機制詳解

    相信接觸過編程的同學應(yīng)該都了解,在訪問任何網(wǎng)頁的時候,會伴隨著許多的事件,例如點擊菜單,移動鼠標等等。那么node.js是如何處理的?下面通過這篇文章就來給大家詳細的介紹下node.js中的事件處理機制,有需要的朋友們可以參考借鑒,下面來一起學習學習吧。
    2016-11-11
  • 基于Node.js的http模塊搭建HTTP服務(wù)器

    基于Node.js的http模塊搭建HTTP服務(wù)器

    這篇文章主要為大家介紹了基于Node.js的http模塊來搭建HTTP服務(wù)器的示例過程詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步
    2022-02-02
  • nodejs教程之制作一個簡單的文章發(fā)布系統(tǒng)

    nodejs教程之制作一個簡單的文章發(fā)布系統(tǒng)

    本文主要講述了使用nodejs制作一個簡單的文章發(fā)布系統(tǒng),使用mongodb數(shù)據(jù)庫,時間比較緊,功能做的也比較簡單,僅僅是增刪改查,外加附近上傳,有相同需求的小伙伴可以參考下
    2014-11-11
  • 深入淺析NodeJs并發(fā)異步的回調(diào)處理

    深入淺析NodeJs并發(fā)異步的回調(diào)處理

    這篇文章主要介紹了NodeJs并發(fā)異步的回調(diào)處理的相關(guān)資料,需要的朋友可以參考下
    2015-12-12

最新評論