国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

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

2024-05-06 15:40:25
字體:
來源:轉載
供稿:網友

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 (與) 所有條件均需滿足

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 平度市| 台南市| 木里| 平武县| 高青县| 玉屏| 永嘉县| 呼玛县| 海晏县| 麟游县| 砚山县| 大兴区| 仲巴县| 镇坪县| 香格里拉县| 涪陵区| 越西县| 双流县| 乌审旗| 剑川县| 汉源县| 梁山县| 延长县| 即墨市| 安国市| 拜城县| 山东省| 永德县| 南川市| 全州县| 东丽区| 莫力| 金堂县| 赣州市| 梅州市| 钟祥市| 阿拉善右旗| 中西区| 图木舒克市| 龙南县| 南靖县|