Node.js & Express & MongoDB Leve1

مُشاهدة المُستوى الأول كامل

1مُقدمة المُستوى الأول
2project setup
  1. Download node.js
  2. Install expressjs
  3. npm install -g nodemon
  4. To show file
    res.sendFile("./views/home.html", {root: __dirname});

Download files

3Connect project to MongoDB

👉 npm i mongoose


const mongoose = require('mongoose');

mongoose.connect("YOUR LINK").then(() => {
  app.listen(port, () => {
    console.log(`http://localhost:${port}`);
  });
 })
 .catch((err) => {
   console.log(err);
 });

👉 mongodb.com

👉 Download files

4⭐ Send data to database

1 Make a post request by using the <form> </form> 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 }));

3Defining 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;

4in app.js using .save()

  
const Article = require("./models/articleSchema");
 
app.post("/all-articles", (req, res) => {
  const article = new Article(req.body);

  article
    .save()
    .then( result => {
      res.redirect("/");
    })
    .catch( err => {
      console.log(err);
    });
});

ORUsing Model.create()

  
const Article = require("./models/articleSchema");
 
app.post("/all-articles", (req, res) => {
  Article
    .create(req.body)
    .then( result => {
      res.redirect("/");
    })
    .catch( err => {
      console.log(err);
    });
});

Download files

5⭐ Get data from database - Install ejs from

👉 npm i ejs

👉 in app.js file app.set('view engine', 'ejs')

👉 You should put your .ejs files in views folder

👉 install VS code extension : EJS Language Support

👉 res.render('index', { } )

إتعامل ويك أنك بداخل الــ views فولدر

👉 modelName.find()

المصدر

Download files

6Static files & auto refresh
Serving static files in Express (images & CSS & JavaScript..)

👉 in app.js file app.use(express.static('public'))

👉 put all your static files in public folder

إتعامل ويك أنك بداخل الــ public فولدر

Auto refresh

1npm i livereload connect-livereload

2in app.js :

 
const path = require("path");
const livereload = require("livereload");
const liveReloadServer = livereload.createServer();
liveReloadServer.watch(path.join(__dirname, 'public'));
 
 
const connectLivereload = require("connect-livereload");
app.use(connectLivereload());
 
liveReloadServer.server.once("connection", () => {
  setTimeout(() => {
    liveReloadServer.refresh("/");
  }, 100);
});

3 in package.json :

"scripts": {
  "start": "node app.js",
  "watch": "nodemon --ext *"
}

4npm run watch

*livereload

Download files

7Project setup

Best Practices for Naming Files & Folders :

👉 - app.js

👉 - public (css files & images)

👉 - views (partials folder & .ejs files)

👉 - models (modelSchema.js)

👉 - routes

👉 - controllers

👉 - package.json

👉 - package-lock.json

Download files

8Components in ejs

ejs.co

Download files

9Send data to database (project)

Download files

10Get data from database (project)

Download files

11req.params.idto get single object from database

المصدر

Download files

12Mongoose Timestamps (Date & Time)

ترتيب الأكواد مهم جداً فى ملف app.js

1in Schema file:

const userSchema = new Schema(
{
fireName: String,
lastName: String,
},
{ timestamps: true }
);

2npm i moment& docs

Download files

13⭐ Delete data from mongoDB

1npm install method-override

2in app.js

var methodOverride = require('method-override')
app.use(methodOverride('_method'))

3in ejs file:


<form action="/edit/<%= item._id %>?_method=DELETE" method="post">
    <button>Delete</button>
</form>

4Create a delete request in app.js :

 
app.delete("/edit/:id", (req, res) => {
  User.deleteOne({ _id: req.params.id }).then((result) => {
  res.redirect("/");
  });
}); 

Download files

14Task & Solution

Download files

15 ⭐ Update Data in MongoDB

نفس خطوات حذف الdata مع بعض التعديلات :

1?_method=PUT


<form action="/edit/<%= item._id %>?_method=PUT" method="post">
    <button>Update</button>
</form>

2usingModel.findByIdAndUpdate()OR Model.updateOne()

 
app.put("/edit/:id", (req, res) => {
  User.updateOne({_id: req.params.id}, req.body)
    .then(() => {
      res.redirect("/");
  });
}); 

المصدر

Download files

16 MongoDB Query Operators

👉 Age = 24 User.find({ age: 24 })

👉 Age > 24 User.find({ age: {$gt: 24} })

👉 Age >= 24 User.find({ age: {$gte: 24} })

👉$or User.find({ $or: [{fireName: "ali"}, {lastName: "ali"}] })

المصدر

Download files

17Task solution

Download files

18express.Router

Download files

19MVC (Model-View-Controller)

MVC :هى طريقة لتنظيم وترتيب ملفات المشروع لكى تُسهل عملية تعديل المشروع فى المُستقبل وتقسيم المشروع الى أجزاء صغيرة وبالتالى التحكم فى كل جزء من أجزاء الموقع بسهولة.

20Deploy on render.com

1in app.js : 👉 const port = process.env.PORT || 3001;

2in package.json :

 
"scripts": {
  "start": "node app.js",
  "watch": "nodemon --ext *"
},

3 render.com 👉 Build Command:npm install

21مُلخص المستوى الأول

👉 YouTube video: https://www.youtube.com

😡
انت مشغل الـ AdBlock !!

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

تنبيه هام ✋

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