DEV Community

Erasmus Kotoka
Erasmus Kotoka

Posted on

Codes on

Virtual

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const userSchema = new Schema({
firstName: String,
lastName: String,
});

// Define a virtual for the user's full name
userSchema.virtual('fullName').get(function() {
return ${this.firstName} ${this.lastName};
});

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

// Usage
const user = new User({ firstName: 'John', lastName: 'Doe' });
console.log(user.fullName); // Output: "John Doe"

Population
const postSchema = new Schema({
title: String,
content: String,
author: { type: Schema.Types.ObjectId, ref: 'User' }
});

const Post = mongoose.model('Post', postSchema);

// Populate author when querying posts
Post.find()
.populate('author') // Fetches associated User document
.exec((err, posts) => {
console.log(posts);
});

indexing
const productSchema = new Schema({
name: String,
price: Number,
category: String
});

// Create an index on the category field
productSchema.index({ category: 1 });

const Product = mongoose.model('Product', productSchema);

// Now, queries on category will be faster
Product.find({ category: 'Electronics' }, (err, products) => {
console.log(products);
});

Do your career a big favor. Join DEV. (The website you're on right now)

It takes one minute, it's free, and is worth it for your career.

Get started

Community matters

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay