app.
js
const mongoose = require('mongoose');
// MongoDB connection string
const mongoURI = 'mongodb://localhost:27017/app';
mongoose.connect(mongoURI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
const db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log('Connected to MongoDB successfully!');
// Define a schema
const schema = new mongoose.Schema({
name: String,
age: Number,
address: String
});
// Define a model
const Model = mongoose.model('Model', schema);
// CRUD Operations
// CREATE (Insert multiple documents)
const createDocuments = async () => {
const docs = [
{ name: 'Logeshkumar', age: 30, address: '123 Main St' },
{ name: 'Kalaiselvan', age: 25, address: '456 Elm St' },
{ name: 'Tej', age: 40, address: '789 Oak St' },
{ name: 'Manoj', age: 35, address: '321 Pine St' }
];
await Model.insertMany(docs);
console.log('Documents inserted successfully');
};
// READ
const readDocuments = async () => {
const docs = await Model.find();
console.log('Documents found:', docs);
};
// UPDATE
const updateDocument = async () => {
const doc = await Model.findOneAndUpdate({ name: 'Logeshkumar' }, { age: 31 }, { new: true
});
console.log('Document updated:', doc);
};
// DELETE
const deleteDocument = async () => {
const doc = await Model.findOneAndDelete({ name: 'Logeshkumar' });
console.log('Document deleted:', doc);
};
const performCRUDOperations = async () => {
await createDocuments(); // INSERT MULTIPLE
await readDocuments();
await updateDocument();
await readDocuments();
await deleteDocument();
await readDocuments();
// Close the connection
mongoose.connection.close();
};
performCRUDOperations().catch(console.error);
});