Loading

Quipoin Menu

Learn • Practice • Grow

mongodb / Mongoose CRUD and Validation
interview

Q1. How do you create a document with Mongoose?
Two ways: using new and save, or using create():
const user = new User({ name: 'John', age: 30 }); await user.save(); // or const user = await User.create({ name: 'John', age: 30 });

Q2. How do you query documents with Mongoose?
Mongoose provides static and instance methods:
const users = await User.find({ age: { $gt: 25 } }); const user = await User.findOne({ email: 'john@example.com' }); const userById = await User.findById('507f1f77bcf86cd799439011');
Query results are Mongoose documents with added methods.

Q3. How do you update documents?
Using updateOne, updateMany, or findAndUpdate:
await User.updateOne({ name: 'John' }, { age: 31 }); const user = await User.findByIdAndUpdate(id, { age: 31 }, { new: true });
The { new: true } option returns the updated document.

Q4. How do you delete documents?
Use deleteOne, deleteMany, or findAndDelete:
await User.deleteOne({ name: 'John' }); const user = await User.findByIdAndDelete(id);
Check the result for deletedCount.

Q5. How do you add validation in Mongoose?
Validation is defined in the schema:
const userSchema = new mongoose.Schema({ name: { type: String, required: [true, 'Name is required'] }, age: { type: Number, min: 18, max: 100 }, email: { type: String, validate: { validator: v => /S+@S+.S+/.test(v), message: props => `${props.value} is not a valid email!` } } });
Validation runs on save() and create().