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() 获取结果。以上就是nodejs如何实现数据库增删改查的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号