Skip to main content

MongoDB and Nodejs Apps with Mongoose

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.
These code samples were used to create a Node.js RESTful API since you are performing CRUD functions when creating an API. Read through that tutorial to see these commands in action. This article will be more of a reference for the various commands and their usage.


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');
Let’s get to the commands.


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

#Sample Model for Users

// 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
We will then create the mongoose Model by calling mongoose.model. We can also do more with this like creating specific methods. This is a good place to create a method to hash a password.


Custom Method

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

// create a schema
var userSchema ...

// custom method to add string to end of name
// you can create more important methods like name validations or formatting
// you can also do queries and find similar users 
userSchema.methods.dudify = function() {
  // add some stuff to the users name
  this.name = this.name + '-dude'; 

  return this.name;
};

// 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;

SAMPLE USAGE

Now we have a custom model and method that we can call in our code:
// if our user.js file is at app/models/user.js
var User = require('./app/models/user');
  
// create a new user called chris
var chris = new User({
  name: 'Chris',
  username: 'sevilayha',
  password: 'password' 
});

// call the custom method. this will just add -dude to his name
// user will now be Chris-dude
chris.dudify(function(err, name) {
  if (err) throw err;

  console.log('Your new name is ' + name);
});

// call the built-in save method to save to the database
chris.save(function(err) {
  if (err) throw err;

  console.log('User saved successfully!');
});
This is a very useless custom method, but the idea for how to create a custom method and use it stands. We can use this for making sure that passwords are hashed before saving, having a method to compare passwords, find users with similar attributes, and more.


Run a Function Before Saving

We also want to have a created_at variable to know when the record was created. We can use the Schema pre method to have operations happen before an object is saved.
Here is the code to add to our Schema to have the date added to created_at if this is the first save, and to updated_at on every save:
// on every save, add the date
userSchema.pre('save', function(next) {
  // get the current date
  var currentDate = new Date();
  
  // change the updated_at field to current date
  this.updated_at = currentDate;

  // if created_at doesn't exist, add to that field
  if (!this.created_at)
    this.created_at = currentDate;

  next();
});
Now on every save, we will add our dates. This is also a great place to hash passwords to be sure that we never save plaintext passwords.
We can also define more things on our models and schemas like statics and indexes. Be sure to take a look at the mongoose docs for more information.


Create

We’ll be using the User method we created earlier. The built-in savemethod on mongoose Models is what is used to create a user:
// grab the user model
var User = require('./app/models/user');

// create a new user
var newUser = User({
  name: 'Peter Quill',
  username: 'starlord55',
  password: 'password',
  admin: true
});

// save the user
newUser.save(function(err) {
  if (err) throw err;

  console.log('User created!');
});


Read

There are many reasons for us to query our database of users. We’ll need one specific user, all users, similar users, and many more scenarios. Here are a few examples:

FIND ALL

// get all the users
User.find({}, function(err, users) {
  if (err) throw err;

  // object of all the users
  console.log(users);
});

FIND ONE

// get the user starlord55
User.find({ username: 'starlord55' }, function(err, user) {
  if (err) throw err;

  // object of the user
  console.log(user);
});

FIND BY ID

// get a user with ID of 1
User.findById(1, function(err, user) {
  if (err) throw err;

  // show the one user
  console.log(user);
});

QUERYING

You can also use MongoDB query syntax.
// get any admin that was created in the past month

// get the date 1 month ago
var monthAgo = new Date();
monthAgo.setMonth(monthAgo.getMonth() - 1);

User.find({ admin: true }).where('created_at').gt(monthAgo).exec(function(err, users) {
  if (err) throw err;

  // show the admins in the past month
  console.log(users);
});


Update

Here we will find a specific user, change some attributes, and then re-save them.

GET A USER, THEN UPDATE

// get a user with ID of 1
User.findById(1, function(err, user) {
  if (err) throw err;

  // change the users location
  user.location = 'uk';

  // save the user
  user.save(function(err) {
    if (err) throw err;

    console.log('User successfully updated!');
  });

});
Remember that since we created the function to change the updated_atdate, this will also happen on save.

FIND AND UPDATE

An even easier method to use since we dont have to grab the user, modify, and then save. We are just issuing a mongodb findAndModify command.
// find the user starlord55
// update him to starlord 88
User.findOneAndUpdate({ username: 'starlord55' }, { username: 'starlord88' }, function(err, user) {
  if (err) throw err;

  // we have the updated user returned to us
  console.log(user);
});

FIND BY ID AND UPDATE

// find the user with id 4
// update username to starlord 88
User.findByIdAndUpdate(4, { username: 'starlord88' }, function(err, user) {
  if (err) throw err;

  // we have the updated user returned to us
  console.log(user);
});


Delete

GET A USER, THEN REMOVE

// get the user starlord55
User.find({ username: 'starlord55' }, function(err, user) {
  if (err) throw err;

  // delete him
  user.remove(function(err) {
    if (err) throw err;

    console.log('User successfully deleted!');
  });
});

FIND AND REMOVE

// find the user with id 4
User.findOneAndRemove({ username: 'starlord55' }, function(err) {
  if (err) throw err;

  // we have deleted the user
  console.log('User deleted!');
});

FIND BY ID AND REMOVE

// find the user with id 4
User.findByIdAndRemove(4, function(err) {
  if (err) throw err;

  // we have deleted the user
  console.log('User deleted!');
});

Comments

Popular posts from this blog

Scenario : Cloud Computing

ASP.NET Core - MVC Setup

Here we will set up the MVC framework in our FirstAppDemo application. We will proceed by building a web application on top of the ASP.NET Core, and more specifically, the ASP.NET Core MVC framework. We can technically build an entire application using only middleware, but ASP.NET Core MVC gives us the features that we can use to easily create HTML pages and HTTP-based APIs. To setup MVC framework in our empty project, follow these steps − Install the  Microsoft.AspNet.Mvc  package, which gives us access to the assemblies and classes provided by the framework. Once the package is installed, we need to register all of the services that ASP.NET MVC requires at runtime. We will do this inside the  ConfigureServices  method. Finally, we need to add middleware for ASP.NET MVC to receive requests. Essentially this piece of middleware takes an HTTP request and tries to direct that request to a C# class that we will write. Step 1  − Let us go to the NuGet package manager by ri

SQL Server Tutorial - Date functions

1. Get month names with month numbers: In this query we will learn about  How to get all month names with month number in SQL Server . I have used this query to bind my dropdownlist with month name and month number. 1 2 3 4 5 6 7 8 9 10 11 12 ;WITH months(MonthNumber) AS (      SELECT 0      UNION ALL      SELECT MonthNumber+1      FROM months      WHERE MonthNumber < 12 ) SELECT DATENAME(MONTH,DATEADD(MONTH,-MonthNumber,GETDATE())) AS [MonthName],Datepart(MONTH,DATEADD(MONTH,-MonthNumber,GETDATE())) AS MonthNumber FROM months ORDER BY Datepart(MONTH,DATEADD(MONTH,-MonthNumber,GETDATE())) ; 2. Get name of current month: In this query we will learn about  How to get name of current month in SQL Server . 1 select DATENAME(MONTH, GETDATE()) AS CurrentMonth 3. Get name of day: In this query we will learn about  How to get name of day in SQL Server . 1 select DATENAME(WEEKDAY, GETDATE()) AS TodayI