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: '[email protected]',
  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 Holmes';

Or you can use a combination, setting some data when the object is created, and adding additional data afterwards:

var newUser = new User({
  email: '[email protected]',
  lastLogin : Date.now()
});
newUser.name = 'Simon Holmes';
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.69.143