The MERN stack is a popular web development stack that consists of MongoDB, Express, React, and Node.js. When working with the MERN stack, it's common to use MongoDB as the database. MongoDB is a NoSQL database that uses a document-oriented data model, which makes it a good fit for web applications that require flexible and scalable data storage.
Here are some examples of database operations you could include in a chapter on MongoDB:
Connecting to a MongoDB database:
const { MongoClient } = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'
// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'test';
async function main() {
// Use connect method to connect to the server
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('device');
// the following code examples can be pasted here...
return 'done.';
}
main()
.then(console.log)
.catch(console.error)
//.finally(() => client.close());
Inserting data into a collection:
const createResult = await collection.insertOne({ name: "John Doe",age: 35,});
console.log("Created documents =>", createResult);
Querying data from a collection:
const findResult = await collection.find({ name: "John Doe" }).toArray();
console.log('Found documents =>', findResult);
Updating data in a collection:
const updateResult = await collection.updateOne({ name: "John Doe" }, { $set: { age: 31 } });
console.log("Updated document", updateResult);
Deleting data from a collection:
const deleteResult = await collection.deleteOne({ name: "John Doe" });
console.log("Deleted document", deleteResult);
These are some basic examples of MongoDB operations that you could include in a chapter on the database. You can build upon these examples to cover more advanced topics, such as indexing, aggregation, and transaction management in MongoDB.