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);
});

Heroku

Amplify your impact where it matters most β€” building exceptional apps.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

Image of DataStax

AI Agents Made Easy with Langflow

Connect models, vector stores, memory and other AI building blocks with the click of a button to build and deploy AI-powered agents.

Get started for free

πŸ‘‹ Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay