Haɗawa da Neman MongoDB a ciki Express

A cikin aiwatar da haɓaka aikace-aikacen yanar gizo, haɗawa da tambayar bayanan bayanai wani yanki ne mai mahimmanci. A cikin wannan labarin, za mu bincika yadda ake haɗawa da kuma bincika bayanan MongoDB a cikin Express aikace-aikacen. MongoDB sanannen zaɓi ne don adana bayanai a cikin aikace-aikacen Node.js saboda sassauƙarsa da girmansa.

 

Haɗa MongoDB tare da Express:

Don farawa, muna buƙatar shigar da kunshin Mongoose ta npm kuma saita haɗin kai zuwa bayanan MongoDB.

npm install express mongoose

Ga misalin yadda ake haɗa MongoDB tare da Express:

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

 

Bayanan Tambaya daga MongoDB:

Bayan samun nasarar haɗawa zuwa MongoDB, za mu iya yin tambayoyin bayanai a cikin Express aikace-aikacen. Ga misalin neman bayanai daga MongoDB ta amfani da Mongoose:

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

A cikin misalin da ke sama, muna ayyana tsari don abin "User" kuma muna amfani da samfurin don yin tambayoyin bayanai. Anan, muna tambayar duk masu amfani da shekaru sama da 18 ko daidai kuma mu shigar da sakamakon da aka dawo.

 

Kammalawa: A cikin wannan labarin, mun bincika yadda ake haɗawa da kuma tambayar bayanan MongoDB a cikin Express aikace-aikacen. Yin amfani da MongoDB azaman bayanan bayanai don aikace-aikacen Node.js yana ba mu zaɓi mai sassauƙa da ƙarfi. Ta amfani da Mongoose, za mu iya yin tambayoyin bayanai cikin sauƙi da gina amintattun aikace-aikacen yanar gizo.