فى هذا الدرس سوف نقوم بإرسال وحفظ الـ data فى الــ database وذلك عن طريق :

  1. Connect app.js with mongo database
  2. Create schema & model in models folder
  3. Make a post request & Save the data to the database

1- Connect app.js with mongo database

How to connect express with mongodb
  1. npm i mongoose
  2. Get the connection link from
    mongodb.com > Databases > Build a Database > Create cluster > connect
  3. in app.js :
     
    const mongoose = require('mongoose');
     
    mongoose.connect("connection link")
      .then( result => {
        app.listen(3000);
      })
      .catch( err => {
        console.log(err);
      }); 
    
الفيديو
تحميل الملفات

2- Create schema & model in models folder

Defining schema & Creating a model

Create a folder called "models" and inside it create a file; for example articleSchema.js

inside this file :

 
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
 
// define the Schema (the structure of the article)
const articleSchema = new Schema({
  title: String,
  summary: String,
  body: String,
});
 
 
// Create a model based on that schema
const Article = mongoose.model("Article", articleSchema);
 
 
// export the model
module.exports = Article; 
الفيديو
تحميل الملفات

3- Save the data to the database

What is POST request ?

- is HTTP Request Method

- is used to send data to a server

How to make a POST requst with Node.js & Express

1 We make a post request by using the <form> </form> HTML element with action & method attributes

<input> must have name attribute

 
<form action="/all-articles" method="POST">
    <label for="title">Article title:</label>
    <input type="text" id="title" name="title" required>
 
 
    <label for="summary">Article summary:</label>
    <input type="text" id="summary" name="summary" required>
 
 
 
    <label for="body">Article body:</label>
    <textarea id="body" name="body" required></textarea>
 
 
    <button class="create">Create</button>
</form> 

2 in app.js :
app.use(express.urlencoded({ extended: true }));

 
const Article = require("./models/articleSchema");
 
 
app.post("/all-articles", (req, res) => {
  const article = new Article(req.body);
 
  console.log(req.body);
 
  article
    .save( )
    .then( result => {
      res.redirect("/all-articles");
    })
    .catch( err => {
      console.log(err);
    });
}); 
المصادر
الفيديو
تحميل الملفات
😡
انت مشغل الـ AdBlock !!

ياريت تقفله لوسمحت 😊 😊

تنبيه هام ✋

إذا كانت الإعلانات مزعجة بالنسبة لك، فيُمكنك التبرع ب50$ وسيتم إيقاف الإعلانات لمدة شهر لجميع زوار الموقع 🧡 ويُمكنك التواصل معنا عن طريق صفحة الفيس بوك