Setting up the MongoDB database
- Use MongoDB Atlas
- Free cloud hosted sandbox database
- Not for production, but great for development and prototyping it here.
- Could also use Compose, ScaleGrid, ObjectRocket.
- Create an account here: create an account
- Then build da cluster button
- Select region, then create cluster
- Collections, add my own data
- Database name: local_library
- Collection name: Collection0
- Then overview, connect
- Allow access from anywhere
- Create a user (see below)
- Connect your application
Install Mongoose
- Now we can set up install and mongoose
npm install mongoose
Connect to MongoDb
- In app.js, we put the following text in. Make sure to use the above database string.
- This code creates the default connection to the database, and also binds to the error event (to print errors to the console)
//Set up mongoose connection
var mongoose = require('mongoose');
var mongoDB = 'insert_your_database_url_here';
mongoose.connect(mongoDB, { useNewUrlParser: true , useUnifiedTopology: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
Defining the LocalLibrary Schema
- Need to create modules for each model
- Create the folder for models, then add these folders:
/express-locallibrary-tutorial //the project root
/models
author.js
book.js
bookinstance.js
genre.js
Author Model
- Let’s create the author schema
- This defines author as having a String SchemeType for first and family names.
- Also a date field for dates of birth and death
- There is also a virtual for the AuthorSchema. It’s called URL that returns the URL required to ge ta particular instance of the model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var AuthorSchema = new Schema(
{
first_name: {type: String, required: true, maxLength: 100},
family_name: {type: String, required: true, maxLength: 100},
date_of_birth: {type: Date},
date_of_death: {type: Date},
}
);
// Virtual for author's full name
AuthorSchema
.virtual('name')
.get(function () {
return this.family_name + ', ' + this.first_name;
});
// Virtual for author's lifespan
AuthorSchema.virtual('lifespan').get(function() {
var lifetime_string = '';
if (this.date_of_birth) {
lifetime_string = DateTime.fromJSDate(this.date_of_birth).toLocaleString(DateTime.DATE_MED);
}
lifetime_string += ' - ';
if (this.date_of_death) {
lifetime_string += DateTime.fromJSDate(this.date_of_death).toLocaleString(DateTime.DATE_MED)
}
return lifetime_string;
});
// Virtual for author's URL
AuthorSchema
.virtual('url')
.get(function () {
return '/catalog/author/' + this._id;
});
//Export model
module.exports = mongoose.model('Author', AuthorSchema);
Book Model
- Also create a book model
- Similar to the author model
- Main difference – created two references to other models – Author and Genre
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BookSchema = new Schema(
{
title: {type: String, required: true},
author: {type: Schema.Types.ObjectId, ref: 'Author', required: true},
summary: {type: String, required: true},
isbn: {type: String, required: true},
genre: [{type: Schema.Types.ObjectId, ref: 'Genre'}]
}
);
// Virtual for book's URL
BookSchema
.virtual('url')
.get(function () {
return '/catalog/book/' + this._id;
});
//Export model
module.exports = mongoose.model('Book', BookSchema);
BookInstance Model
- BookInstance represents a specific copy of a book that someone might borrow. Information about whether the copy is available, what date it is back, what imprint or version.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BookInstanceSchema = new Schema(
{
book: { type: Schema.Types.ObjectId, ref: 'Book', required: true }, //reference to the associated book
imprint: {type: String, required: true},
status: {type: String, required: true, enum: ['Available', 'Maintenance', 'Loaned', 'Reserved'], default: 'Maintenance'},
due_back: {type: Date, default: Date.now}
}
);
// Virtual for bookinstance's URL
BookInstanceSchema
.virtual('url')
.get(function () {
return '/catalog/bookinstance/' + this._id;
});
//Export model
module.exports = mongoose.model('BookInstance', BookInstanceSchema);
Genre Model – Challenge
- Now need to create genre model.
- It needs to have a String SchemaType called name
- Name should be required to have between 3 and 100 characters.
- Needs a virtual, called URL,
- Need to be able to export the model
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var GenreSchema = new Schema(
{
name: {type: String, required: true, minLength: 3, maxLength: 100};
}
);
// Virtual for author's URL
GenreSchema
.virtual('url')
.get(function () {
return '/catalog/genre/‘ + this._id;
});
//Export model
module.exports = mongoose.model(‘Genre’, GenreSchema);
Testing it out!
- Sample data: populatedb.js
npm install async
node populatedb <<string>>