ఎక్స్‌ప్రెస్‌లో MongoDBని కనెక్ట్ చేయడం మరియు ప్రశ్నించడం

వెబ్ అప్లికేషన్‌లను అభివృద్ధి చేసే ప్రక్రియలో, డేటాబేస్‌కు కనెక్ట్ చేయడం మరియు ప్రశ్నించడం అనేది కీలకమైన భాగం. ఈ కథనంలో, మేము ఎక్స్‌ప్రెస్ అప్లికేషన్‌లో మొంగోడిబి డేటాబేస్‌కి ఎలా కనెక్ట్ అవ్వాలి మరియు ప్రశ్నించాలి. MongoDB అనేది Node.js అప్లికేషన్‌లలో దాని సౌలభ్యం మరియు స్కేలబిలిటీ కారణంగా డేటాను నిల్వ చేయడానికి ఒక ప్రసిద్ధ ఎంపిక.

 

MongoDBని ఎక్స్‌ప్రెస్‌తో కనెక్ట్ చేస్తోంది:

ప్రారంభించడానికి, మేము npm ద్వారా Mongoose ప్యాకేజీని ఇన్‌స్టాల్ చేయాలి మరియు MongoDB డేటాబేస్‌కు కనెక్షన్‌ను కాన్ఫిగర్ చేయాలి.

npm install express mongoose

MongoDBని ఎక్స్‌ప్రెస్‌తో ఎలా కనెక్ట్ చేయాలో ఇక్కడ ఒక ఉదాహరణ ఉంది:

const mongoose = require('mongoose');
const express = require('express');
const app = express();

// Connect to the MongoDB database
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log('Connected to MongoDB');
    // Continue writing routes and logic in Express
  })
  .catch((error) => {
    console.error('Error connecting to MongoDB:', error);
  });

// ... Other routes and logic in Express

app.listen(3000, () => {
  console.log('Server started');
});

 

MongoDB నుండి డేటాను ప్రశ్నిస్తోంది:

MongoDBకి విజయవంతంగా కనెక్ట్ అయిన తర్వాత, మేము ఎక్స్‌ప్రెస్ అప్లికేషన్‌లో డేటా ప్రశ్నలను నిర్వహించవచ్చు. Mongooseని ఉపయోగించి MongoDB నుండి డేటాను ప్రశ్నించే ఉదాహరణ ఇక్కడ ఉంది:

const mongoose = require('mongoose');

// Define the schema and model
const userSchema = new mongoose.Schema({
  name: String,
  age: Number
});

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

// Query data from MongoDB
User.find({ age: { $gte: 18 } })
  .then((users) => {
    console.log('List of users:', users);
    // Continue processing the returned data
  })
  .catch((error) => {
    console.error('Error querying data:', error);
  });

పై ఉదాహరణలో, మేము "యూజర్" ఆబ్జెక్ట్ కోసం స్కీమాను నిర్వచించాము మరియు డేటా ప్రశ్నలను నిర్వహించడానికి మోడల్‌ని ఉపయోగిస్తాము. ఇక్కడ, మేము 18 కంటే ఎక్కువ లేదా అంతకంటే ఎక్కువ వయస్సు ఉన్న వినియోగదారులందరినీ ప్రశ్నించాము మరియు తిరిగి వచ్చిన ఫలితాలను లాగ్ చేస్తాము.

 

ముగింపు: ఈ కథనంలో, మేము ఎక్స్‌ప్రెస్ అప్లికేషన్‌లో మొంగోడిబి డేటాబేస్‌కు కనెక్ట్ చేయడం మరియు ప్రశ్నించడం ఎలాగో అన్వేషించాము. Node.js అప్లికేషన్‌ల కోసం డేటాబేస్ సొల్యూషన్‌గా MongoDBని ఉపయోగించడం మాకు సౌకర్యవంతమైన మరియు శక్తివంతమైన ఎంపికను అందిస్తుంది. ముంగిసను ఉపయోగించడం ద్వారా, మేము డేటా ప్రశ్నలను సులభంగా నిర్వహించగలము మరియు నమ్మదగిన వెబ్ అప్లికేషన్‌లను రూపొందించగలము.