Loading

Quipoin Menu

Learn • Practice • Grow

mongodb / Mongoose CRUD and Validation
tutorial

Mongoose CRUD and Validation

Now that you have your Mongoose models set up, let's perform CRUD operations! Mongoose provides a rich set of methods for creating, reading, updating, and deleting documents. Plus, it automatically validates data based on your schema definitions.

CREATE: Saving Documents

There are two ways to create documents in Mongoose:
  1. Create an instance and call `save()`
  2. Use `Model.create()`

Method 1: new + save()
async function createUser() {
  try {
    const user = new User({
      name: 'Alice',
      email: 'alice@example.com',
      age: 28
    });
   
    const savedUser = await user.save();
    console.log('User saved:', savedUser);
  } catch (err) {
    console.error('Validation error:', err.message);
  }
}

Method 2: Model.create()
async function createProduct() {
  try {
    const product = await Product.create({
      name: 'Laptop',
      price: 999,
      category: 'electronics'
    });
    console.log('Product created:', product);
  } catch (err) {
    console.error('Error:', err);
  }
}

Mongoose automatically validates data before saving. If validation fails, it throws an error with details about what went wrong.

READ: Finding Documents

Find All
async function getAllProducts() {
  try {
    const products = await Product.find();
    console.log('Products:', products);
    return products;
  } catch (err) {
    console.error(err);
  }
}

Find with Conditions
<!-- Find by field -->
const electronics = await Product.find({ category: 'electronics' });

<!-- Comparison operators -->
const cheapProducts = await Product.find({
  price: { $lt: 50 }
});

<!-- Chain methods -->
const sortedProducts = await Product
  .find({ category: 'electronics' })
  .sort({ price: -1 })
  .limit(5);

Find One Document
const user = await User.findOne({ email: 'alice@example.com' });

<!-- Find by ID (most common) -->
const product = await Product.findById('65a1b2c3d4e5f6a7b8c9d0e1');

UPDATE: Modifying Documents

Update One
<!-- Find and update -->
const result = await User.updateOne(
  { email: 'alice@example.com' },
  { $set: { age: 29 } }
);

console.log(result.modifiedCount); <!-- 1 if updated -->

Find by ID and Update (returns updated document)
const updatedUser = await User.findByIdAndUpdate(
  userId,
  { $set: { name: 'New Name' } },
  { new: true } <!-- Return the updated document -->
);

DELETE: Removing Documents

Delete One
const result = await User.deleteOne({ email: 'alice@example.com' });
console.log(result.deletedCount);

Find by ID and Delete
const deletedUser = await User.findByIdAndDelete(userId);
<!-- Returns the deleted document -->

Validation Examples

With this schema:
const userSchema = new mongoose.Schema({
  name: { type: String, required: [true, 'Name is required'] },
  email: {
    type: String,
    required: true,
    unique: true,
    match: [/^S+@S+.S+$/, 'Please use a valid email address']
  },
  age: {
    type: Number,
    min: [18, 'Must be at least 18'],
    max: [120, 'Invalid age']
  }
});

Validation errors are descriptive:
try {
  await User.create({ name: 'John', age: 10 });
} catch (err) {
  console.log(err.errors.age.message); <!-- 'Must be at least 18' -->
}

Two Minute Drill

  • Create: `new Model()` + `save()` or `Model.create()`.
  • Read: `find()`, `findOne()`, `findById()` with chainable methods.
  • Update: `updateOne()`, `findByIdAndUpdate()`.
  • Delete: `deleteOne()`, `findByIdAndDelete()`.
  • Validation happens automatically – catch errors to see what failed.
  • Use `{ new: true }` with findAndUpdate to get the updated document.

Need more clarification?

Drop us an email at career@quipoinfotech.com