Chat Application - Mongoose

9/18/2021 NodeJsExpressJsSocketIo

# Express:

# 1.Install:

Để tạo 1 application đơn giản thì có thể dùng công cụ Express application generator (opens new window)

$ express --no-view <app>
1

Loại trừ view engine vì application client dùng reactJs

# Mongoose

# 1.Install:
$ npm i mongoose
1
# 2.Setup mongoose:
//  File: app.js
/* Mongoose Connect */
const dbHost = process.env.DB_HOST || 'localhost';
const dbPort = process.env.DB_PORT || '27017';
const dbName = process.env.DB_NAME || 'chat_app';
const dbConnectUrl = `mongodb://${dbHost}:${dbPort}/${dbName}`;

function listen() {
  app.listen(process.env.PORT || 5000, () => {
        console.log("Server has started!")
    })
}

mongoose.connect(dbConnectUrl, {
  keepAlive: 1,
  useNewUrlParser: true,
  useUnifiedTopology: true
}).then(() => {
    app.listen(process.env.PORT || 5000, () => {
        console.log("Server has started!")
    })
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

Hàm connect return về 1 promise, resolved nó để run express application.

# 3.Model:

Với chat app thì đơn giản có thể tạo 2 model: User (lưu dữ liệu user) và Room (lưu dữ liệu room và message).

  • User:

    Schema: Define các option của field như name, datatype, giá trị default, các ràng buộc giá trị,..

    // File: models/user.js
    const mongoose = require('mongoose');
    const Schema = mongoose.Schema;
    
    const UserSchema = new Schema({
      name: {
        type: String,
        required: true,
        unique: true
      },
      avatar: {
        type: String,
        default: 'assets/images/avatar.png'
      },
      password: {
        type: String,
        required: true
      },
    });
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19

    Mã hóa và verify password:

    pre: Define handle trước khi gọi 'save' lưu dữ liệu sẽ mã hóa.

    Method isValidPassword: Verify password.

    const bcrypt = require('bcrypt');
    ...
    
    UserSchema.pre(
      'save',
      async function(next) {
        const user = this;
        const hash = await bcrypt.hash(this.password, 10);
    
        this.password = hash;
        next();
      }
    );
    
    UserSchema.methods = {
      /**
       * Validate password
       */
      isValidPassword: async function (password) {
      	const user = this;
      	const compare = await bcrypt.compare(password, user.password);
         
        return compare;
      }
    };
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25

    Model: Define model từ schema

    module.exports = mongoose.model('User', UserSchema);
    
    1
  • Room:

    Schema: Tương tự như user. messages là 1 array và user cần refer map với tên model của User (khi get dữ liệu room có thể get cả dữ liệu của user bằng method .populate('user', 'name username'))

    // File: models/room.js
    const RoomSchema = new Schema({
      name: {
        type: String,
        required: true,
        trim: true,
        maxlength: 400,
        default: ''
      },
      messages: [
        {
          msgType: {type: String, default: 'text'},
          text: {type: String, default: ''},
          data: {type: Object, default: {}},
          date: {type: Date, default: Date.now()},
          user: {type: Schema.ObjectId, ref: 'User'}
        }
      ],
      users: [
        {
          user: {type: Schema.ObjectId, ref: 'User'},
          createdAt: {type: Date, default: Date.now}
        }
      ]
    });
    ...
    module.exports = mongoose.model('Room', RoomSchema);
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
  • Require các model tại app.js

    require('./models/user');
    require('./models/room');
    
    1
    2

Series:

Github: https://github.com/ninhnguyen22/chat_app (opens new window)