Node.js and MongoDB are a pair made for each other. Being able to use JSON across the board and JavaScript makes development very easy. This is why you get popular stacks like the MEAN stack that uses Node, Express (a Node.js framework), MongoDB, and AngularJS.

CRUD is something that is necessary in most every application out there. We have to create, read, update, and delete information all the time.

Today we’ll be looking at code samples to handle CRUD operations in a Node.js, ExpressJS, and MongoDB application. We’ll use the popular Node package, mongoose.

 

What Is Mongoose?

mongoose is an object modeling package for Node that essentially works like an ORM that you would see in other languages (like Eloquent for Laravel).

Mongoose allows us to have access to the MongoDB commands for CRUD simply and easily. To use mongoose, make sure that you add it to you Node project by using the following command:

npm install mongoose --save

Now that we have the package, we just have to grab it in our project:

var mongoose = require('mongoose');

We also have to connect to a MongoDB database (either local or hosted):

mongoose.connect('mongodb://localhost/myappdatabase');

Defining a Model

Before we can handle CRUD operations, we will need a mongoose Model. These models are constructors that we define. They represent documents which can be saved and retrieved from our database.

Mongoose Schema The mongoose Schema is what is used to define attributes for our documents.

Mongoose Methods Methods can also be defined on a mongoose schema. These are methods

// grab the things we need
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

// create a schema
var userSchema = new Schema({
  name: String,
  username: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  admin: Boolean,
  location: String,
  meta: {
    age: Number,
    website: String
  },
  created_at: Date,
  updated_at: Date
});

// the schema is useless so far
// we need to create a model using it
var User = mongoose.model('User', userSchema);

// make this available to our users in our Node applications
module.exports = User;

This is how a Schema is defined. We must grab mongoose and mongoose.Schema. Then we can define our attributes on our userSchema for all the things we need for our user profiles. Also notice how we can define nested objects as in the meta attribute.

The allowed SchemaTypes are:

  • String
  • Number
  • Date
  • Buffer
  • Boolean
  • Mixed
  • ObjectId
  • Array

Our NodeJS Code looks like

awesomescreenshot-online-javascript-beautifier-2019-07-25-18-07-10

http://inheritxdev.net/knowledgebase/wp-content/uploads/2019/07/AwesomeScreenshot-Online-JavaScript-beautifier-2019-07-25-18-07-10.png

below link help you to setup pm2 in server environment

http://inheritxdev.net/knowledgebase/how-to-start-and-automatically-restart-nodejs-server-using-pm2/

You may also like

Leave a Reply