Models in the express app

Share

Read Previous: https://codewithsudeep.com/sudeep/javascript/working-with-database-in-express-app/

Introduction

The Model is the component of MVC that carries out the domain logic. To put it simply, the data transmitted between the database and the user interface is handled by this logic. The term “domain object” or “domain entity” refers to the model.

In the express, models are responsible for creating a logical layer to communicate with the database. Model file in the express app contains information like key name, data type and constraints, relations, and triggers.

Models are elaborate constructors created from definitions in Schemas. A document is a particular instance of a model. Models use the underlying MongoDB database to create and read documents.

Read on Wikipedia

Constructing Model

To construct a model, we use the js package mongoose. First, import shema and model object from the package.

const { Schema, model } = require('mongoose')

Then, we construct a schema for an entity using the schema method.

const userSchema = new Schema({
    name : {
        type : String,
        required : true,
    },
    email:{
        type : String,
        required : true,
        unique : true,
    },
    password : {
        type : String,
        required : true,
    },
})

Then, we call the model('collection_name',shema) method to construct the desired model. Also, it creates a table in the database after compilation.


const User = model('users', userSchema)

The unique name of the collection that your model is for is the first argument. Mongoose searches for your model name’s lowercase, plural form automatically. Consequently, in the example above, model User refers to the database’s collection of users.

if you are writing model logic in a separate file then you can export the reference to this model.

Compiled Model File

// userModel.js

const { Schema, model } = require('mongoose')

const userSchema = new Schema({
    name : {
        type : String,
        required : true,
    },
    email:{
        type : String,
        required : true,
        unique : true,
    },
    password : {
        type : String,
        required : true,
    },
})

const User = model('users', userSchema)

module.exports = User

Using Model To insert data

Before using the model, you should know the concepts like MongoDB model inbuilt functions. Here are the complete references.

To insert data into the table:

const User = require('./userModel.js')
User.create({
  name:"cws",
  email:"cws@mail.com",
  password:"pass321"
}).catch(err=>console.log(err))

When the above code is executed it inserts the data into database.

MongoDB user collection

Complete code:

// index.js

const express = require('express')
const app = express()
const mongodb = require('mongoose')
const mongodb_url = `mongodb://localhost:27017/backendapp?retryWrites=true&w=majority`
const User = require('./UserModel')

mongodb.connect(mongodb_url,{
  useNewUrlParser: true,
  useUnifiedTopology: true,
}).then(()=>console.log("+ Mongo Database Connected!!"))
.catch(error=>console.log(error))

User.create({
  name:"cws",
  email:"cws@mail.com",
  password:"pass321"
}).catch(err=>console.log(err))


app.listen(3000, () => {
  console.log(`+ Express App Started\n+ Port:${3000}`)
})

// userModel.js

const { Schema, model } = require('mongoose')

const userSchema = new Schema({
    name : {
        type : String,
        required : true,
    },
    email:{
        type : String,
        required : true,
        unique : true,
    },
    password : {
        type : String,
        required : true,
    },
})

const User = model('user', userSchema)

module.exports = User

Share
Sudeep Mishra

Sudeep Mishra

Healing

%d bloggers like this: