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() {


This content originally appeared on DEV Community and was authored by Erasmus Kotoka

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


This content originally appeared on DEV Community and was authored by Erasmus Kotoka


Print Share Comment Cite Upload Translate Updates
APA

Erasmus Kotoka | Sciencx (2024-11-01T03:04:39+00:00) Codes on. Retrieved from https://www.scien.cx/2024/11/01/codes-on/

MLA
" » Codes on." Erasmus Kotoka | Sciencx - Friday November 1, 2024, https://www.scien.cx/2024/11/01/codes-on/
HARVARD
Erasmus Kotoka | Sciencx Friday November 1, 2024 » Codes on., viewed ,<https://www.scien.cx/2024/11/01/codes-on/>
VANCOUVER
Erasmus Kotoka | Sciencx - » Codes on. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2024/11/01/codes-on/
CHICAGO
" » Codes on." Erasmus Kotoka | Sciencx - Accessed . https://www.scien.cx/2024/11/01/codes-on/
IEEE
" » Codes on." Erasmus Kotoka | Sciencx [Online]. Available: https://www.scien.cx/2024/11/01/codes-on/. [Accessed: ]
rf:citation
» Codes on | Erasmus Kotoka | Sciencx | https://www.scien.cx/2024/11/01/codes-on/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.