Reader small image

You're reading from  Mongoose for Application Development

Product typeBook
Published inAug 2013
Reading LevelIntermediate
PublisherPackt
ISBN-139781782168195
Edition1st Edition
Languages
Right arrow
Author (1)
Simon Holmes
Simon Holmes
author image
Simon Holmes

Simon Holmes started his journey as a web developer in the late 1990s. He built his first website for a project at university and soon saw what the industry had to offer when he promptly sold it! Following university, Simon worked his way through the ranks of design agency life, learning the skills of becoming a full-stack web developer. From server management and database design to building dynamic UIs from Photoshop files, it all fell under Simon's remit. Having witnessed first-hand the terrible JavaScript code so prevalent in the early 2000s, Simon is very much enjoying its resurgence as a powerful, structured language. Simon now works in SaaS, which is very heavy on the JavaScript.
Read more about Simon Holmes

Right arrow

Chapter 5. Interacting with Data – Creation

As we are building an application from the ground up, our first work with data will be creating some and saving it to the database. In this chapter we will:

  • Learn about creating an instance

  • Learn about saving an instance

  • Learn when to use different approaches

  • Add the ability for users to sign up to our MongoosePM application by:

    • Adding new routes

    • Adding new views

    • Adding new controller code

    • Saving the user details in a session so that they stay logged in

  • Outline the steps required to add the ability to create new projects, but let you go for it alone! If you get stuck, you can always download the complete source code to take a look.

Creating an instance


Now that Chapter 4, Interacting with Data – An Introduction has taken care of the housekeeping, it's time to get going and do stuff with data. Theory first, then action!

To do anything meaningful at all, we will have to create an instance. This could be done by retrieving an object from a database, but let's start by creating a new empty instance. We do this by using the new ModelName expression. As our model is called User, to create a new instance we invoke the new User expression.

var newUser = new User();

Adding data to the instance

When creating an instance, you will generally want to add some data to it. The default way of adding data is to pass it to the model constructor as a JavaScript object. For example:

var newUser = new User({
  name: 'Simon Holmes',
  email: 'simon@theholmesoffice.com',
  lastLogin : Date.now()
});

Although you can also add data to the instance after it has been created, as shown in the following:

var newUser = new User();
newUser.name = 'Simon...

Saving an instance


So far we have created an instance, and put some data to it, but it only exists in the application. Saving it to the database is a really simple operation.

Note

Your Mongoose connection must be open for this to work.

After we have created our newUser and given it some data, we save it in the following way:

newUser.save( function( err ){
  if(!err){
    console.log('User saved!');
  }
});

This .save method is an example of an instance method, because it operates directly on the instance, rather than the model. Note that the parameter it takes is a callback function to run when the save operation has been made to the database. As we saw back in Chapter 1, Introducing Mongoose to the Technology Stack, writing to a database is a blocking operation, but the .save method provides a non-blocking asynchronous way of doing this, allowing the Node process to carry on and deal with other requests.

This is a good thing for our application, but it means that any operations that you want...

Creating and saving database entry in one step


We don't always need to run all the commands separately and can simplify do things by creating and saving the database entry in one step. There are two ways of doing this.

Chaining methods

The first way is to chain the newUser and .save commands into one line, for example:

var newUser = new User({
  name: 'Simon Holmes',
  email: 'simon@theholmesoffice.com',
  lastLogin : Date.now()
}).save( function( err ){
  if(!err){
    console.log('User saved!');
  }
});

The Model.create() method

The second way is to use a single-model method, which combines the new and the save operations into one command. This method takes two parameters. First is the data object, and the second is the callback function that is to be executed after the instance has been saved to the database.

So the blueprint for this method is:

ModelName.create(dataObject,callback)

Let's see this in operation, using our trusty User model:

User.create({
  name: 'Simon Holmes',
  email: 'simon...

CRUD – create data


Now we're going to take what we've just learned, and use it to add the ability to create users in our application. If we look back to the routes we set up in app.js, we can see that we have two routes for creating a user, the form itself and the form action.

app.get('/user/new', user.create);     // Create new user form
app.post('/user/new', user.doCreate);  // Create new user action

Adding a new user form

To display the form in an HTML page, we need to do two things:

  • Create the Jade template

  • Link the template to the route

Adding the Jade template

By default Express will install with two Jade template files, layout.jade and index.jade. The layout template contains the HTML skeleton, including the DTD, <head>, and <body> tags. The index template extends the layout template inside the <body> tag.

For our MongoosePM application, we will keep this simple approach, and create a new extension template for each new page template we need. This is a great approach for...

Summary


In this chapter, we have learned how to use the default methods provided by Mongoose to create and save new database entries, based on our schemas and models. We have seen that you can run a quick single command, or have greater control and flexibility through issuing a series of separate commands.

In our project, we have now added the ability to create users and projects.

Coming up in the next chapter, we're going to look at how to use Mongoose to query the database, to find the data we want and use it to populate a web page.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Mongoose for Application Development
Published in: Aug 2013Publisher: PacktISBN-13: 9781782168195
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Simon Holmes

Simon Holmes started his journey as a web developer in the late 1990s. He built his first website for a project at university and soon saw what the industry had to offer when he promptly sold it! Following university, Simon worked his way through the ranks of design agency life, learning the skills of becoming a full-stack web developer. From server management and database design to building dynamic UIs from Photoshop files, it all fell under Simon's remit. Having witnessed first-hand the terrible JavaScript code so prevalent in the early 2000s, Simon is very much enjoying its resurgence as a powerful, structured language. Simon now works in SaaS, which is very heavy on the JavaScript.
Read more about Simon Holmes