• Stars
    star
    116
  • Rank 303,894 (Top 6 %)
  • Language
    CSS
  • Created about 12 years ago
  • Updated about 10 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Simple Blog example with Express, Jade, Mongoose

expressSimpleBlog

Simple Blog example with Express, Jade, Mongoose

This example covers following topics;

  • express
  • mongoose
  • jade
  • session
  • schema decoration
  • security
  • routes
  • ideal project structure

Quick links ;

mongoose express jade

Basic express installation

  npm install -g express
  
  express
  
  create : .
     create : ./package.json
     create : ./app.js
     create : ./public
     create : ./public/javascripts
     create : ./public/images
     create : ./public/stylesheets
     create : ./public/stylesheets/style.css
     create : ./routes
     create : ./routes/index.js
     create : ./routes/user.js
     create : ./views
     create : ./views/layout.jade
     create : ./views/index.jade
  
     install dependencies:
       $ cd . && npm install
  
     run the app:
       $ node app

Schema examples

###Single

  User = new Schema({
        name:{
            type:String,
            required:false,
            default: ""
        },
        username:{
            type:String,
            validate:[validator({
                length:{
                    min:3,
                    max:20
                }
            }), "username"],
            required:false,
            default: "defaultusername"
        },
        password:{
            type:String,
            required:true
        },
        email:{
            type:String,
            required:true
        },
        registerDate:{
            type:Date,
            required:true,
            default: Date.now
        },
        loginDate:{
            type:Date,
            required:false
        }
    });

###Embedded

  Comment = new Schema({
        text:{
            type:String,
            required:true
        },
        author:{
            type:String,
            validate:[validator({
                length:{
                    min:3,
                    max:20
                }
            }), "username"],
            required:false,
            default:"anonymous"
        },
        createDate:{
            type:String,
            required:false,
            default: Date.now
        }
    });

    Blog = new Schema({
        title:{
            type:String,
            required:true
        },
        text:{
            type:String,
            required:true
        },
        author:{
            type:String,
            validate:[validator({
                length:{
                    min:3,
                    max:20
                }
            }), "username"],
            required:false,
            default:"anonymous"
        },
        comments: {type: [Comment]},
        createDate:{
            type:Date,
            required:false,
            default: Date.now
        }
    });

##Mongoose best practises ###1 Find specific user by username

  Model.findOne({username: "johndoe"}, function(err, userName) {
    if (err) {
      next("technical error occured");
    } else {
      if (userInfo) {
        next("User details : " + userInfo);
      } else {
        next("User not found")
      }
    }
  });

###2 Find users have age under 18 and sort them desc

  var query = Model.find({age: {$lt: 18}}).sort({age: -1});
  query.execFind({}, function(err, users) {
    if (err) {
      next("Technical error occured");
    } else {
      if (users) {
        next("How could you registered to my system? You will be banned one by one!!!");
        users.forEach(function(user) {
          user.status = "banned";
          user.save(function(err) {
            if (err) {
              next("Technical error occured while banning user : " + user);
            } else {
              next("Go find another buggy system to yourself!!!");
            }
          });
        })
      } else {
        next("System has no security vulnerability:)")
      }
    }
  });

###3 Insert subdocument

  Model.findOne({username: "johndoe"}, function(err, userInfo) {
    if (err) {
      next("Technical error occured");
    } else {
      if (userInfo) {
        var SubModel = new SubModel();// Assumed to be initialized somewhere above in the sky
        SubModel.projectName = "SocialAuth";
        SubModel.projectLanguage = "PHP";
        SubModel.projectCost = 100;
        userInfo.projects.push(SubModel);
        userInfo.save(function(err) {
          if (err) {
            next("Technical error again.What a stable system i am");
          } else {
            next("New project experience added to user : " + userInfo.username);
          }
        });
      }
    }    
  });

###4 Update subdocument

  Model.update(
            {
                username: "johndoe", project.name: "SocialAuth"
            },
            {
                $inc: {'projects.$.cost': 200}
            },
            //In order to update all documents. If you set this false, it will update only first found document
            {multi: true},
            function(err, result) {
              if (err) {
                next("Technical error occured");
              } else {
                next("Project finished its first year so i am updating its price as 200$ :)");
              }
            
            }

MongoDB credentials setup for project

In this project some user authentication methods have been used, so you can seup your mongodb user for your db;

  mongo localhost

  use <blog>

  db.addUser("test", "123456")

Added user test for b blog. This will be used in project config

Nested functions to waterfall

In express applications, there is a view problem on nested functions. Let's eee it in an example;

  Model1.findOne({username: "johndoe"}, function(err, userInfo) {
    if (err) {
      ........
    } else {
      Model2.find({age: userInfo.age}, function(err, model2Info) {
        if(err) {
          ......
        } else {
          Model3.find({something: model2Info.count}, function(err, model3Info) {
            if (err) {
              ........
            } else {
              .................
              ............
              ..............
              //4 more nested function
              Model8.find({}, function(err, someInfo) {
                if(err) ............
                else
                  next("I have found the result but i don't want to use this result because of this nasty nested function!!!");
              });
            }
          });
        }
      });
    }
  });

In real projects, there are such cases, so our hero on this case is;

step or async

I prefer async, because i used them and async wins :) async also has 3466 stars but step has 1091. There are several ways to re-implement above nested function by using async. We can use waterfall model(For more info please refer to project github documentation)

  async.waterfall([
    function(callback) {
      Model1.findOne({username: "johndoe"}, function(err, userInfo) {
        callback(null, userInfo);
      });    
    },
    function(userInfo, callback) {
      Model2.find({age: userInfo.age}, function(err, model2Info) {
        callback(null, model2Info);
      
      });
    },
    function(model2Info, callback) {
      Model3.find({something: model2Info.count}, function(err, model3Info) {
        var dummy = 15;
        callback(null, model3Info, dummy);
      });
      
    },
    function(modelInfo, count, callback) {
      var some = foo(modelInfo, count);
      callback(null, some);
    },
    ..........................
    ......................
    ,
    function(modelInfo, callback) {
      callback(null, modelInfo);  
    }
    ], function(err, result) {
      if (err) .......
      else
        next("Result found and i am happy to use this result");
    });

More Repositories

1

token-based-auth-backend

Token Based Authentication Backend Project Written in NodeJS
JavaScript
168
star
2

hands-on-kubernetes

Hands-On Kubernetes Webinar Series Materials
69
star
3

nodes-restful-api

Simple Blogging RESTful API with NodeJS and Restify
JavaScript
45
star
4

microservices

Go gRPC Microservices
Go
29
star
5

aiws

AI Driven AWS CLI that helps you to generate and use AWS commands to manage your resources in AWS
Go
29
star
6

live-coding-roadmap

Roadmap of the Live Coding Projects & Ideas
18
star
7

spring-boot-microservices

Java
18
star
8

demory

Cloud-Native Distributed In-Memory Database
Go
18
star
9

kubernetes-node-example

Example Node.js Deployment to Kubernetes Cluster
JavaScript
17
star
10

nodeschool-restful-api

Sample RESTful API for NodeSchool Workshop
JavaScript
15
star
11

twitter-stream

Twitter stream and real time notification backed by Apache Kafka
JavaScript
12
star
12

spring-security-demo

Spring Security Demo
Java
12
star
13

youcontribute

Challenge yourself to contribute on opensource projects
Java
11
star
14

transactional-outbox-sample

Java
11
star
15

grpc-microservices-in-go

Go
11
star
16

swiss

swiss
Go
10
star
17

token-based-authentication-system-wtih-andgularjs-nodejs

Token Based Authentication System with AngularJS & NodeJS
9
star
18

awesome-go-microservices

Go
8
star
19

nodejsinaction-simpleblog

NodeJS in Action Course Simple Blog Example
JavaScript
8
star
20

spring-kafka-pubsub

Spring + Kafka + PostgreSQL example with K8s observation by using Botkube
Java
8
star
21

huseyinbabal

Huseyin BABAL
7
star
22

media

Simple client library for http mock testing
JavaScript
7
star
23

leetcode

Leetcode Problems & Solutions
Java
7
star
24

designpatterns

Design Patterns Code Examples
Java
7
star
25

nodejsinaction-frontend

NodeJS in Action Course Simple Blog Frontend Project
JavaScript
6
star
26

connect-hazelcast

Hazelcast session store for Connect and Express
JavaScript
6
star
27

hexagonal-architecture

Hexagonal Architecture in Java Simplified
Java
6
star
28

twitter-stream-docker

Dockerized Twitter Stream Stack
JavaScript
5
star
29

lru-cache

Go
5
star
30

raft-pseudocode

Dummy Golang Implementation of Raft Consensus Algorithm
Go
5
star
31

tx-concurrency

tx-concurrency
Java
5
star
32

awesome-spring-jpa

Java
5
star
33

web-push-service

NodeSchool Web Push Webinar
JavaScript
5
star
34

RealtimeChatLaravel

Realtime Chat Application with ModulusIO and Laravel
PHP
4
star
35

mastering-angularjs-directives

Examples about AngularJS custom directives
HTML
4
star
36

grpc-in-action

https://bit.ly/grpc-in-action
Go
4
star
37

tf-k8s-workshop

Kubernetes Automaton & Application Deployment & Monitoring with Terraform
HCL
4
star
38

grpc-in-30-minutes

TypeScript
4
star
39

java-code-samples

Java code samples for my blog
Java
4
star
40

demory-cli

Go
4
star
41

awesome-spring-transactions

Java
4
star
42

restapp

10 Golden Rules for Spring Boot RESTful API
Java
4
star
43

microservices-proto

Proto Files for gRPC Microservices
Shell
3
star
44

go-scratch-example

Golang Scratch Docker Image Example
Go
3
star
45

github-service

Sample Github Service for NodeSchool Workshop
JavaScript
3
star
46

helm-charts

Smarty
3
star
47

go-channel-usecases

Go
3
star
48

spring-mongo-docker

Spring Mongo Docker Project for Docker Workshop
Java
2
star
49

awesome-gh-actions

awesome-gh-actions
2
star
50

jQueryGameOfLife

Conway's Game of Life Implementation in jQuery
JavaScript
2
star
51

docker_workshop

Istanbul Coders Workshop for Scalable Systems with Docker and Consul
Shell
2
star
52

botkube-plugins-playground

Botkube Plugin System Showcase
Go
2
star
53

realtime-chat

Realtime Chat Application with ModulusIO and NodeJS
HTML
2
star
54

RealtimeChat

Realtime Chat Application with ModulusIO, Spring Boot, Websockets, and MongoDB
HTML
2
star
55

spring-boot-argocd

spring-boot-argocd
Smarty
2
star
56

grpc-ping-pong

Go
2
star
57

quizzer

quizzer
Go
2
star
58

microservices-gitops

microservices-gitops
Smarty
2
star
59

realtimepythonchat

Real-time chat applcation with Flask, Flsk-Socket IO
HTML
2
star
60

completablefuture-playground

Java
2
star
61

grpc-microservices

Grpc Microservices
1
star
62

wp-xmlrpc-client

Wordpress XML-RPC Client
PHP
1
star
63

spring-elasticsearch-admin

Elasticsearch Admin developed by using Spring MVC, Twitter Bootstrap, and AngularJS
Java
1
star
64

firebase-realtime-chat

REal time chat app with AngularJS & Firebase
JavaScript
1
star
65

nodejs-lazyload

JavaScript
1
star
66

sshcon

sshcon lets you manage your ssh connection easily
Shell
1
star
67

jquery-best-practices

jQuery best practices by examples
CSS
1
star
68

saas-billing

saas
Go
1
star
69

SpringMongoDBDataRestExample

Spring MongoDB Data Rest Example for Java Code Geeks Article
Java
1
star
70

java-memory-leak

1
star
71

demory-client-go

Go SDK for Demory
1
star
72

KubernetesService

Kubernetes Service
Java
1
star
73

express-gmaps

ExpressJS Google Maps Example
HTML
1
star
74

ebay-node

Ebay Node.js Client
JavaScript
1
star
75

restful-chat-service

Restful Chat Serice
Java
1
star
76

homebrew-tap

Homebrew Formulas
Ruby
1
star
77

hazelcast-cloud-sdk-go-new

Go
1
star
78

infinite-scalable-docker

Inifinite Scalable Systems with Docker & Docker Machine & Docker Swarm
JavaScript
1
star
79

maze-generator-solver

Maze Generator / Solver Demo
JavaScript
1
star
80

awesome-goreleaser

Go
1
star
81

infra

Infra tool
Go
1
star