Mongo installation

Reference novice tutorial: www.runoob.com/mongodb/mon… Installation under Linux

Sudo apt - get the install libcurl4 openssl wget HTTP: / / https://fastdl.mongodb.org/linux/mongodb-linux-x86_64-ubuntu1604-4.2.8.tgz# Select the appropriate version to downloadTar - ZXVF mongo - Linux - x86_64 - ubuntu1604-4.2.8. TGZ# decompressionMv mongo - SRC - r4.2.8 / usr /local/mongodb4                          Copy the decompression package to the specified directory
Copy the code

You can create the data and log folders under Mongodb4, or you can follow the tutorial and choose to create them under /var/lib

sudo mkdir -p /var/lib/mongo
sudo mkdir -p /var/log/mongodb
sudo chown `whoami` /var/lib/mongo     # set permissions
sudo chown `whoami` /var/log/mongodb   # set permissions
Copy the code

Starting the mongodb Service

mongod --dbpath /var/lib/mongo --logpath /var/log/mongodb/mongod.log --fork
Copy the code

Go to the bin directory to start mongodb

$ cd /usr/local/mongodb4/bin
$ ./mongo

Copy the code

Directing a profile

MongoDB is a document-oriented, Schema-independent database that can store any type of document data in a collection, making it ideal for Node.js applications (the data format it can handle is very similar to the data format in the front-end and back-end JS scripts, avoiding the need to convert back and forth between rows and data objects).

In this paper, Moogoose is used to quickly establish a model object for mongodb, which can realize the access and add, delete, change and check of mongodb database.

jade

Jade is a popular Node.js template engine that has the following characteristics:

1. Use indentation

With two Spaces by default, the following code can be interpreted as

ABC

 p
   span abc
Copy the code

2. Use DocType5 for automatic insertion

Use the post-H5 docType

3. Block keyword

Block is a special keyword that allows other view files to be embedded in this location.

4. Enclose attributes in parentheses

A (href=#,another=attribute,dynamic=someVariable) My link easy to embed variables

5. Embed variables with #{}

p welcome back ,#{user.name}

Jade writes the template for the main page

index.jade

extends layout 
block body 
  if (authenticated)
    p Welcome back, #{me.first}
      a(href="/logout") Logout
  else    
    p Welcome new visitor 
    ul 
      li:  a(href="/login") Login 
      li:  a(href="/signup") Signup
Copy the code

signup.jade

extents layout 
block body   
  form(action="/signup",method="POST",enctype='multipart/form-data')
    fieldset 
      legend Sign up
      p
        label First 
        input(name="user[first]",type="text")
      p 
        label Last 
        input(name="user[last]",type="text")
      p 
        label Email 
        input(name="user[email]",type="text")
      p 
        label Password 
        input(name="user[password]",type="password")
      p 
        button Submit 
      p 
        a(href="/") Go back

Copy the code

login.jade

extend layout block body form(action="/login",method="POST",enctype='multipart/form-data') fieldset legend Log in if(signupEmail) p Congratulations on signing up! Please login below. p label Email li: a(href="/login") Login li: a(href="/signup") SignupCopy the code

signup.jade

extents layout 
block body   
  form(action="/signup",method="POST",enctype='multipart/form-data')
    fieldset 
      legend Sign up
      p
        label First 
        input(name="user[first]",type="text")
      p 
        label Last 
        input(name="user[last]",type="text")
      p 
        label Email 
        input(name="user[email]",type="text")
      p 
        label Password 
        input(name="user[password]",type="password")
      p 
        button Submit 
      p 
        a(href="/") Go back
​
Copy the code

login.jade

extend layout block body form(action="/login",method="POST",enctype='multipart/form-data') fieldset legend Log in if(signupEmail) p Congratulations on signing up! Please login below. p label Email input(name="user[email]",type="text",value=signupEmail) p label Password input(name="user[password]",type="password") p button submit p a(href='/') Go backCopy the code

layout.jade

doctype 
html 
  head 
    title MongoDB example 
  body 
    h1 My first MongoDB app 
    hr
    block body
Copy the code

Index.js defines the template rendering engine and places the Jade file under the default rendering folder /views

app.set('view engine'.'jade')
app.set('view options', {layout:false})
/* Define the route */
app.get('/'.function(req,res){
    res.render('index')
})
app.get('/login'.function(req,res){
    res.render('login')
})
app.get('/signup'.function(req,res){
    res.render('signup')})Copy the code

Mongodb connections and Modeling

/* * @Author: kkkokra * @Date: 2021-05-01 08:31:23 * @LastEditTime: 2021-05-02 22:59:41 * @FilePath: /mongodb-exercise/mongo.js */

var mongoose = require('mongoose');
// Connect to the database, this database needs to be established, and in the background to start the Mongo service, can connect successfully
mongoose.connect('mongodb://localhost/myWebsite');
// Create a connection object
var db=mongoose.connection
db.on('error'.console.error.bind(console.'connection error:'))
db.once('open'.function() {
    // we're connected! , a correct message is displayed indicating that the connection is successful
    console.log('we are connected! ')});// Create a document template
var userSchema=mongoose.Schema({
    firstName:String.lastName:String.email:String.password:String
})
//User is the model object of the User collection
var User=mongoose.model('User',userSchema)
//Event.ensureIndexes(function (err) {
    //if (err) return handleError(err);
/ /});
// Make sure all indexes are created
User.on('index'.function (err) {
    if (err) console.error(err);
    else console.log('ensure index') // error occurred during index creation
  })
// Expose the model object
module.exports = {mongoose,User}
Copy the code

The login

app.get('/login'.function(req,res){
    res.render('login')
})
app.post('/login',multipartMiddleware,function(req,res){

  User.findOne({'email':req.body.user.email,'password':req.body.user.password}, function (err, person) {
    if (err) throw err;
    if(! person)return res.send('<p>User not found.Go back and try again</p>')
    console.log('login : find a person')
    req.session.logged_in=person._id.toString()
    console.log('1',req.session.logged_in)
    res.redirect('/')})Copy the code

registered

app.get('/signup'.function(req,res){
    res.render('signup')
})

app.post('/signup',multipartMiddleware,function(req,res){
    console.log(req.body)
    var newUser = new User(req.body.user);
    newUser.save(function(err){
        if(err) throw err
        else console.log('save the user information')
    })
    res.redirect('/login/'+req.body.user.email)
})
app.get('/login/:signupEmail'.function(req,res){
    res.render('login', {signUpEmail:req.params.signupEmail})
})
Copy the code

Automatic login

app.use(function(req,res,next){
    console.log('2',req.session.logged_in,typeof(req.session.logged_in))
    if(req.session.logged_in){
        res.locals.authenticated=true
        User.findOne({'_id':req.session.logged_in}, function (err, person) {
            if (err) throw err;
            if(! person)return console.log('not exist')
            res.locals.me=person
            console.log('relogin: find a person ')
            next()
        })
    }
    else {
        res.locals.authenticated=false
        next()
    }
})
app.set('view engine'.'jade')
app.set('view options', {layout:false})
/* Define the route */
app.get('/'.function(req,res){
    res.render('index')
})
app.get('/login'.function(req,res){
    res.render('login')
})
app.post('/login',multipartMiddleware,function(req,res){

  User.findOne({'email':req.body.user.email,'password':req.body.user.password}, function (err, person) {
    if (err) throw err;
    if(! person)return res.send('<p>User not found.Go back and try again</p>')
    console.log('login : find a person')
    req.session.logged_in=person._id.toString()
    console.log('1',req.session.logged_in)
    res.redirect('/')})})Copy the code

The cancellation

app.get('/logout'.function(req,res){
  req.session.logged_in=null;
  res.redirect('/')})Copy the code

This completes the log-in and the code is uploaded to Github.