SyntaxStudy
Sign Up
Node.js Beginner 12 min read

MongoDB with Mongoose

Mongoose is an ODM (Object Document Mapper) for MongoDB and Node.js. It provides schema validation, middleware hooks, and a clean API for common database operations. Define schemas to give structure to your MongoDB documents.

Example
// npm install mongoose
const mongoose = require('mongoose');

// Connect to MongoDB:
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/myapp')
    .then(() => console.log('MongoDB connected'))
    .catch(err => { console.error(err); process.exit(1); });

// Define a schema:
const userSchema = new mongoose.Schema({
    username: { type: String, required: true, unique: true, trim: true },
    email:    { type: String, required: true, unique: true, lowercase: true },
    password: { type: String, required: true, minlength: 8 },
    role:     { type: String, enum: ['user', 'admin'], default: 'user' },
    createdAt:{ type: Date, default: Date.now },
});

// Instance method:
userSchema.methods.toSafeObject = function () {
    const { password, ...safe } = this.toObject();
    return safe;
};

const User = mongoose.model('User', userSchema);

// CRUD operations:
async function demo() {
    // Create:
    const user = await User.create({ username: 'alice', email: 'alice@example.com', password: 'hashed!' });

    // Find:
    const found = await User.findById(user._id);
    const all   = await User.find({ role: 'user' }).sort({ createdAt: -1 }).limit(10);

    // Update:
    await User.findByIdAndUpdate(user._id, { role: 'admin' }, { new: true });

    // Delete:
    await User.findByIdAndDelete(user._id);
}

module.exports = User;