Create REST-API using sequelize -MariaDB ORM in Nodejs


We had many posts on API and I am moving on sequelize ORM which allows us to perform CURD operation in REST manner or using Modals, just like we done with mongoose.

Sequelize

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.

MariaDB

MariaDB is a community-developed, commercially supported fork of the MySQL relational database management system, intended to remain free and open-source software under the GNU General Public License. The standard installation come with Heidi SQL GUI which help us create and manage database and schemas.

You can download and install it from the official website

Todo API

todos table in Heidi SQL

Our API is used to create the todos ,store in MariaDB , and perform all CURD operations using sequelize modal.

First we need to create the above table in your Maria. Now lets create a basic Nodejs project.

Continue reading Create REST-API using sequelize -MariaDB ORM in Nodejs

How to interact with input in Reactjs


With Browser route we can create beautiful responsive React app on the go. Most of the dynamic applications accepts some feed back from users. How do we get this done.

This will involve the following

  • Setting state for the each input element.
  • Attach it to the value property of the input.
  • Add a button event function and attach it to the render method.

Setting State

I have a one input text field and a button in the component.

import React, { Component } from "react"; 
 
class Comment extends Component {
  constructor(props) {
    super(props);    
    this.state = {      
    };
  }
  
  
  render() {
    return (
      <div className="form-group  m-2 p-2">
        <textarea
          placeholder="Comment here"
          class="form-control"          
          aria-describedby="inputSuccess5Status"
        />
        <button
          className="btn btn-primary m-1 p-2"        >
          Comment
        </button>         
      </div>
    );
  }
}

export default Comment;

In the above Comment component I have used bootstrap to beautify the form with one Text Area and button element. We need to create and attach a state for the Text Area in the constructor, also need to attach the new value with the state, whenever the user enter the comment. So we need to setState the comment in the on Change event handler.

  • Create state
  • Create event handler for on Change
  • attach them to the HTML tags
class Comment extends Component {
  constructor(props) {
    super(props);
    this.onChangeComment = this.onChangeComment.bind(this);
    this.onPostComment = this.onPostComment.bind(this);
     
    this.state = {
      comment: "",
    };
  }
  onChangeComment(e) {
    this.setState({ comment: e.target.value });
  }

  onPostComment(e) {
    try {
      
     console.log('Thank for using react form')
    } catch (error) {
      console.log(error);
    }
  }
  
  render() {
    return (
      <div className="form-group  m-2 p-2">
        <textarea
          placeholder="Comment here"
          class="form-control"
          value={this.state.comment}
          onChange={this.onChangeComment}
          aria-describedby="inputSuccess5Status"
        />
        <button
          className="btn btn-primary m-1 p-2"
          onClick={this.onPostComment}
        >
          Comment
        </button>
         <CommentCard  comments={this.props.comments}/>
      </div>
    );
  }
}

In the above code , created a state comment , event handlers for input and button and bind them in the constructor.

In the on Change event update the state so, each time the user update will change the state.

Finally attach the state and handlers to form elements ( button,Text Area).

Where did can I see the log(‘…’) result ?. well ,open your browser , ctrl+shift+I ( for developer tools) then go to console and you will see the message)

Following React posts deserve good read

How to populate multiple MongoDB objects on the same path in express-node


In Nodejs app we are using mongoose driver for MongoDB, a NoSql database with speed and accuracy. Mongo store data as series of JSON element call document and the collection of document is called a collection , same as table in DBMS.

According to the Mongoose doc Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s)

So we have the following Document , in which we want to populate user information . For simplicity I skipped some of the mongo

[
    { "tags": [
            "5fef1f5187a69346300003a8",
            "5fef1f5187a69346300003a9",
            "5fef1f5187a69346300003aa"
        ],
        "_id": "5fef1f5087a69346300003a7",
        "title": "Title post",
        "content": "It is a good practice to keep styles for different pages  in separate style sheets. Larger project this becomes more applicable. What you do when need to combine them in another ?",
        "user": "5fe4ab1e69b8d525c44ec293",
        "createdAt": "2021-01-01T13:10:40.468Z",
        "updatedAt": "2021-01-03T02:37:55.982Z",
        "__v": 11
    }
]

The document contains a list of posts with user information etc within the Tag ( not listed) . So the posts is a list of objects which should populate and inside each post have a user and list of tags object as well. Our task is to primarily populate the user object and the tags list.

We can do this right now using the find method of modal class accompanied by the populate command as follows

The tags array and the user belong to the posts path , so we have to repeat the population ( one for user and other for tags)

	const tid = req.params['tid']
			Tag.findById(tid).populate({
				path: 'posts',
				populate: {
					path: 'tags'
				},
				populate: {
					path: 'user',
					select: 'name'
				}
			}).populate({
				path: 'posts',
				populate: {
					path: 'tags',
					select: 'tagName'
				}
			}).exec((err, post) => {
				if (err) return handleError(err)
				console.log('tagged posts are ' + post);
				return res.status(200).send(post.posts)


			})

Result

[
    {
       
        "tags": [
            {
                "_id": "5fef1f5187a69346300003a8",
                "tagName": "Test"
            },
            {
                "_id": "5fef1f5187a69346300003a9",
                "tagName": "VM"
            },
            {
                "_id": "5fef1f5187a69346300003aa",
                "tagName": "JS"
            }
        ],
        "_id": "5fef1f5087a69346300003a7",
        "title": "Title post",
        "content": "It is a good practice to keep styles for different pages  in separate style sheets. Larger project this becomes more applicable. What you do when need to combine them in another ?",
        "user": {
            "_id": "5fe4ab1e69b8d525c44ec293",
            "name": "admin"
        },
        "createdAt": "2021-01-01T13:10:40.468Z",
        "updatedAt": "2021-01-03T02:37:55.982Z",
        "__v": 11
    }
]

In the above code we had used the populate inside another populate because the each posts had user element.

Following mongoose post also deserve a good read

How to populate selected fields in a mongo document path in expressjs


In Express-Nodejs app we are using mongoose driver for MongoDB, a NoSql database with speed and accuracy. Mongo store data as series of JSON element call document and the collection of document is called a collection , same as table in DBMS.

According to the Mongoose doc Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s)

So we have the following Document , in which we want to populate user information

[
    {
        "_id": "5fef1f5087a69346300003a7",
        "title": "Title post",
        "content": "It is a good practice to keep styles for different pages  in separate style sheets. Larger project this becomes more applicable. What you do when need to combine them in another ?",
        "user": "5fe4ab1e69b8d525c44ec293",
        "createdAt": "2021-01-01T13:10:40.468Z",
        "updatedAt": "2021-01-03T02:37:55.982Z",
        "__v": 11
    }
]

So the posts is a list of objects which should populate and inside each post have a user object as well. Our task is to primarily populate the specific user object fields.

We can do this right now using the find method of modal class accompanied by the populate command which specify the path and fields to populate as follows, also used a callback function.

const tid = req.params['tid']
			Tag.findById(tid).populate({
				path: 'posts',
				populate: {
					path: 'user',select:'name'
				}
			}).exec((err, post) => {
				if (err) return handleError(err)
				 
				return res.status(200).send(post.posts)


and the response will be as follows

[
    {
        "_id": "5fef1f5087a69346300003a7",
        "title": "Title post",
        "content": "It is a good practice to keep styles for different pages  in separate style sheets. Larger project this becomes more applicable. What you do when need to combine them in another ?",
        "user": {
            "password": "123",
            "posts": [
                "5feebf2b7e30080468ccd4c1",
                "5feec08a7e30080468ccd4c9",
                ]
            "_id": "5fe4ab1e69b8d525c44ec293",
            "name": "admin",             
        },
        "createdAt": "2021-01-01T13:10:40.468Z",
        "updatedAt": "2021-01-03T02:37:55.982Z",
        "__v": 11
    }
]

In the above code we had used the populate inside another populate because the each posts had user element.

We can use populate inside another one , find out how ? Next post will be on that !

Following mongoose post also deserve a good read

Deno : next generation Node


Deno is a Type Script and JavaScript run time which offer more security and flexibility than Nodejs. It is created in Rust language, by the same Nodejs developer . The frame work has the following features

  • Secure by default. No file, network, or environment access, unless explicitly enabled.
  • Supports TypeScript out of the box.
  • Ships only a single executable file.
  • Has built-in utilities like a dependency inspector (deno info) and a code formatter (deno fmt).
  • Has a set of reviewed (audited) standard modules that are guaranteed to work with Deno:

Deno didn’t download all the dependencies and dependencies of decencies as Node does. It uses URL based dependency management.

Wanna learn more about Deno, jump to Deno land

In the upcoming tutorials, I will show you how to’s of Deno.

How to populate and display nested mongo objectin express-node route


In Nodejs app we are using mongoose driver for MongoDB, a NoSql database with speed and accuracy. Mongo store data as series of JSON element call document and the collection of document is called a collection , same as table in DBMS.

According to the Mongoose doc Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s)

So we have the following Document , in which we want to populate user information

[
    {
        "_id": "5fef1f5087a69346300003a7",
        "title": "Title post",
        "content": "It is a good practice to keep styles for different pages  in separate style sheets. Larger project this becomes more applicable. What you do when need to combine them in another ?",
        "user": "5fe4ab1e69b8d525c44ec293",
        "createdAt": "2021-01-01T13:10:40.468Z",
        "updatedAt": "2021-01-03T02:37:55.982Z",
        "__v": 11
    }
]

The document contains a list of posts with user information etc within the Tag ( not listed) . So the posts is a list of objects which should populate and inside each post have a user object as well. Our task is to primarily populate the user object.

We can do this right now using the find method of modal class accompanied by the populate command as follows

const tid = req.params['tid']
			Tag.findById(tid).populate({
				path: 'posts',
				populate: {
					path: 'user'
				}
			}).exec((err, post) => {
				if (err) return handleError(err)
				 
				return res.status(200).send(post.posts)


and the response will be as follows

[
    {
        "_id": "5fef1f5087a69346300003a7",
        "title": "Title post",
        "content": "It is a good practice to keep styles for different pages  in separate style sheets. Larger project this becomes more applicable. What you do when need to combine them in another ?",
        "user": {
            "password": "123",
            "posts": [
                "5feebf2b7e30080468ccd4c1",
                "5feec08a7e30080468ccd4c9",
                ]
            "_id": "5fe4ab1e69b8d525c44ec293",
            "name": "admin",
            "createdAt": "2020-12-24T14:52:14.364Z",
            "updatedAt": "2021-01-03T02:44:41.780Z",
            "__v": 108
        },
        "createdAt": "2021-01-01T13:10:40.468Z",
        "updatedAt": "2021-01-03T02:37:55.982Z",
        "__v": 11
    }
]

In the above code we had used the populate inside another populate because the each posts had user element.

Following mongoose post also deserve a good read

Create REST-API using sequelize-Mysql in Nodejs


We had many posts on API and I am moving on sequelize ORM which allows us to perform CURD operation in REST manner or using Modals, just like we done with mongoose.

Sequelize

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.

MySQL

MySQL is an open-source relational database management system. Its name is a combination of “My”, the name of co-founder Michael Widenius’s daughter, and “SQL”, the abbreviation for Structured Query Language. A workbench , which GUI tool to manage database object is available at MySQL website along with MySQL Downloads

Todo API

todos table in Workbench

Our API is used to create the todos ,store in MySQL DB , and perform all CURD operations using sequelize modal.

First we need to create the above table in your MySQL. Now lets create a basic Nodejs project.

Continue reading Create REST-API using sequelize-Mysql in Nodejs

Create REST-API using sequelize-Postgres in Nodejs


We had many posts on API and I am moving on sequelize ORM which allows us to perform CURD operation in REST manner or using Modals, just like we done with mongoose.

Sequelize

Sequelize is a promise-based Node.js ORM for Postgres, MySQL, MariaDB, SQLite and Microsoft SQL Server. It features solid transaction support, relations, eager and lazy loading, read replication and more.

PostgreSQL

Postgres is an opensource DBMS, it is free and perform faster results. It come with pg-admin web interface which allows navigate through database. You can download and install it from the official website

Todo API

todos table in pg admin

Our API is used to create the todos ,store in pg (PostgreSQL) , and perform all CURD operations using sequelize modal.

First we need to create the above table in your pg. Now lets create a basic Nodejs project.

Continue reading Create REST-API using sequelize-Postgres in Nodejs

How to render mongo object in Reactjs


MongoDB objects are object Id of another document stored in the mongo database. Following is our sample mongo document we want to render in our React front end.

{    
    "_id": "5fef1f5087a69346300003a7",
    "title": "Title post",
    "content": "It is a good practice to keep styles for different pages  in separate style sheets. Larger project this becomes more applicable. What you do when need to combine them in another ?",
    "user": {    
        "_id": "5fe4ab1e69b8d525c44ec293",
        "name": "admin",
        "createdAt": "2020-12-24T14:52:14.364Z",
        "updatedAt": "2021-01-01T13:12:59.084Z",
        "__v": 106
    },
    "createdAt": "2021-01-01T13:10:40.468Z",
    "updatedAt": "2021-01-01T13:10:41.907Z",
    "__v": 3
}

Our task is to render the user object and access its properties

For simplicity I skip the rest of the component code.

render() {
    return (
      <div>
        <div className="card m-2 p-2">
          <h3>{this.state.post.title}</h3>
          <div>{this.state.post.content} </div>
          <div>  Posted By: {Object(this.state.post.user).name}            
     </div>
        </div>
      </div>
    );

React recognize sub document as filed, not as an object. So we have to convert the user to Object ( the highlighted line)

So far we have succeeded to render the MongoDB object

Following React posts deserve good read

How to render mongo document in Reactjs


MongoDB documents are are similar to rows in a relational database and collection as Table .Following is our sample mongo document we want to render in our React front end.

{    
    "_id": "5fef1f5087a69346300003a7",
    "title": "Title post",
    "content": "It is a good practice to keep styles for different pages  in separate style sheets. Larger project this becomes more applicable. What you do when need to combine them in another ?",
    "user": {    
        "_id": "5fe4ab1e69b8d525c44ec293",
        "name": "admin",
        "createdAt": "2020-12-24T14:52:14.364Z",
        "updatedAt": "2021-01-01T13:12:59.084Z",
        "__v": 106
    },
    "createdAt": "2021-01-01T13:10:40.468Z",
    "updatedAt": "2021-01-01T13:10:41.907Z",
    "__v": 3
}

We need to get rendered the post in a React component . To do this we need to do the following

  • Make API call – fetching the post
  • Save the object to state
  • Type cast the object and render

For simplicity I skip the rest of the component code.

State and API Call

....
constructor(props) {
    super(props);

    this.state = {
      post: Object,
   
    };
  }
.....

componentDidMount() {
    const { pid } = this.props.match.params;

    axios
      .get(`http://localhost:3005/post/${pid}`)
      .then((res) => {
        if (res.data) {
          this.setState({ post: res.data});
        }
      })
      .catch((error) => {
        console.log(error);
      });
 
  }

render() {
    return (
      <div>
        <div className="card m-2 p-2">
          <h3>{this.state.post.title}</h3>
          <div>{this.state.post.content} </div>
                 
     </div>
        </div>
      </div>
    );

Our API call return a single post, a mongo document , Note that we initialized the post (parent document) with Object in the constructor.

The data returned by the response object ( post) is a React acceptable object, so we can render it directly without any pain .

In this tutorial you have learned

  • Read parameter list from URL in React
  • API call in React
  • Render mongo document

Following React post/project deserve your attention