CRUD Operations with MongoDB
CRUD (Create, Read, Update, Delete) operations are the core actions performed on a database. Here's how to handle them using MongoDB and Mongoose in Node.js.
1. Create (Insert Data)
Add new records to the database.
const User = mongoose.model('User', userSchema);
const createUser = async () => {
const user = new User({ name: 'John', age: 25 });
await user.save();
console.log('User created:', user);
};
createUser();
2. Read (Retrieve Data)
Fetch records from the database.
const getUsers = async () => {
const users = await User.find(); // Fetch all users
console.log('Users:', users);
};
getUsers();
3. Update (Modify Data)
Update existing records.
const updateUser = async (id) => {
await User.findByIdAndUpdate(id, { age: 30 });
console.log('User updated');
};
updateUser('user_id_here');
4. Delete (Remove Data)
Delete records from the database.
const deleteUser = async (id) => {
await User.findByIdAndDelete(id);
console.log('User deleted');
};
deleteUser('user_id_here');