node.js 中的數據庫增刪改查:連接數據庫:使用 mongoclient 連接到 mongodb 數據庫。插入數據:創建集合并插入數據。刪除數據:使用 deleteone() 刪除數據。更新數據:使用 updateone() 更新數據。查詢數據:使用 find() 和 toarray() 查詢并獲取數據。
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>
登錄后復制
四、更新數據
<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()
獲取結果。