nodejs如何實作資料庫增刪改查

下次还敢
發布: 2024-04-21 06:27:20
原創
790 人瀏覽過

Node.js 中的資料庫增刪改查:連接資料庫:使用 MongoClient 連線到 MongoDB 資料庫。插入資料:建立集合並插入資料。刪除資料:使用 deleteOne() 刪除資料。更新資料:使用 updateOne() 更新資料。查詢資料:使用 find() 和 toArray() 查詢並取得資料。

nodejs如何實作資料庫增刪改查

Node.js 中的資料庫增刪改查

一、連接資料庫

<code class="ts">const MongoClient = require('mongodb').MongoClient;
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);</code>
登入後複製

二、插入資料

<code class="ts">const collection = client.db('myDatabase').collection('myCollection');
await collection.insertOne({ name: 'John Doe', age: 30 });</code>
登入後複製

三、刪除資料

<code class="ts">await collection.deleteOne({ name: 'John Doe' });</code>
登入後複製

#4、更新資料

<code class="ts">await collection.updateOne({ name: 'John Doe' }, { $set: { age: 31 } });</code>
登入後複製

五、查詢資料

<code class="ts">const cursor = await collection.find({ age: { $gt: 30 } });
const results = await cursor.toArray();</code>
登入後複製

#細節說明:

  • 使用MongoClient#連接到MongoDB 資料庫。
  • 建立一個集合(表)並插入資料。
  • 使用 deleteOne()updateOne() 方法刪除和更新資料。
  • 使用 find() 方法查詢數據,並使用 toArray() 來取得結果。

以上是nodejs如何實作資料庫增刪改查的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
最新問題
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!