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 class="ts">const collection = client.db('myDatabase').collection('myCollection');
await collection.insertOne({ name: 'John Doe', age: 30 });
三、删除数据
<code class="ts">await collection.deleteOne({ name: 'John Doe' });
四、更新数据
<code class="ts">await collection.updateOne({ name: 'John Doe' }, { $set: { age: 31 } });
五、查询数据
<code class="ts">const cursor = await collection.find({ age: { $gt: 30 } });
const results = await cursor.toArray();
细节说明:
- 使用
MongoClient
连接到 MongoDB 数据库。 - 创建一个集合(表)并插入数据。
- 使用
deleteOne()
和updateOne()
方法删除和更新数据。 - 使用
find()
方法查询数据,并使用toArray()
获取结果。