How to implement database addition, deletion, modification and query in nodejs

下次还敢
Release: 2024-04-21 06:27:20
Original
769 people have browsed it

Database addition, deletion, modification and query in Node.js: Connect to the database: Use MongoClient to connect to the MongoDB database. Insert data: Create a collection and insert data. Delete data: Use deleteOne() to delete data. Update data: Use updateOne() to update data. Query data: Use find() and toArray() to query and obtain data.

How to implement database addition, deletion, modification and query in nodejs

Database addition, deletion and modification query in Node.js

1. Connect to the database

const MongoClient = require('mongodb').MongoClient; const url = 'mongodb://localhost:27017'; const client = new MongoClient(url);
Copy after login

2. Insert data

const collection = client.db('myDatabase').collection('myCollection'); await collection.insertOne({ name: 'John Doe', age: 30 });
Copy after login

3. Delete data

await collection.deleteOne({ name: 'John Doe' });
Copy after login

4. Update data

await collection.updateOne({ name: 'John Doe' }, { $set: { age: 31 } });
Copy after login

5. Query data

const cursor = await collection.find({ age: { $gt: 30 } }); const results = await cursor.toArray();
Copy after login

Details:

  • UseMongoClientConnect to the MongoDB database.
  • Create a collection (table) and insert data.
  • Use thedeleteOne()andupdateOne()methods to delete and update data.
  • Use thefind()method to query data, and usetoArray()to obtain the results.

The above is the detailed content of How to implement database addition, deletion, modification and query in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!