Our complete code

Now that we have defined our schemas and compiled the models, let's take a look at our /model/db.js file.

var mongoose = require( 'mongoose' ),
dbURI = 'mongodb://localhost/MongoosePM';
mongoose.connect(dbURI);
// Connection events snipped out for brevity

/* ********************************************
      USER SCHEMA
   ******************************************** */
var userSchema = new mongoose.Schema({
  name: String,
  email: {type: String, unique:true},
  createdOn: { type: Date, default: Date.now },
  modifiedOn: Date,
  lastLogin: Date
});

// Build the User model
mongoose.model( 'User', userSchema );

/* ********************************************
      PROJECT SCHEMA
   ******************************************** */
var projectSchema = new mongoose.Schema({
  projectName: String,
  createdOn: { type: Date, default: Date.now },
  modifiedOn: Date,
  createdBy: String,
  contributors: String,
  tasks: String
});

// Build the Project model
mongoose.model( 'Project', projectSchema );

In this code we have done everything we need to before moving on. These are as follows:

  • We required Mongoose
  • We set the connection string for the MongoDB database
  • We defined the User schema
  • We built the User model
  • We defined the Project schema
  • We built the Project model
  • We opened the Mongoose connection to the database

Note that if you have large complex schemas and models, you may want to have separate files for each, and just export the models.

..................Content has been hidden....................

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