Mongoose Schemas

To be able to execute CRUD operations to interact with our database, we have to model our data. By this, we’ll create schemas that will be used to send data. In our example, we’ll create a document posting document details coming from Client and go to Server where the POST method will receive data and will grave it into the database, through our schema.

Server Side

Note that we create also the indexes.

// mongoDB
var mongoose = require('mongoose');
// new object
var mongoSchemas = new Object();

...

 /*
	DOCUMENTS
 */
mongoSchemas.documents = new mongoose.Schema({
	lib_code : String,
	doc_type : String,
	authors : [ String ], //index
	publisher : String,
	subject : String, //index
	pages : Number,
	publishing_date : Date,
	publishing_city : String,
	isbn10 : String, // index
	isbn13 : String,
	description : String,
	title : String, // index
	price : Number,
	copies : [
		{
			copy_id : String,
			acquired_date : Date,
			owner_member_id : String,
			available : Boolean,
			price : Number,
			library_id : String
		}
	],
	created_at : {type : Date, default : Date.now },
	updated_at : { type : Date, default : Date.now }
});

// document indexes
mongoSchemas.documents.index({
	subject : 1,
	isbn10 : 1,
	title : 1,
	authors : 1
});

// exports these mongodb schemas
module.exports = mongoSchemas;
 
...

// mongoDB
var mongoose = require('mongoose');

...

var schemas = require('../bin/schemas.js');

//New documents model
var documents = mongoose.model('documents', schemas.documents);

...

// new subject
router.post('/', function (req, res, next){
	// Start timing now
	console.time("documents.router.post.job.timespan");

	// create new subject document into the collection
	documents.create(req.body, function(err, post){
		if(err) return next(err);
		else {
			//return results
			res.json(post);

			// log
			console.log('documents.router.post');
			console.log('id: '+ req.params.id);
			console.log('post: '+ JSON.stringify(post));
			console.log('query: '+ JSON.stringify(req.query));
			console.log('params: '+ JSON.stringify(req.params));
			console.log('body: '+ JSON.stringify(req.body));

			// Stop timer.
			console.timeEnd('documents.router.post.job.timespan');
			console.log('\n');
		}
	});
});

...

module.exports = router;
 

Client Side

We create a service to use it to get documents information. In this example we pass the subject parameter to get its documents. Also, we can pass the ID to get a specific document that contains the same value in “_id” field of the document on MongoDB documents collection. This service can do CREATE and DELETE operations too, but we’ll concentrate on the CREATE one.

angular.module('myLibraryApp.services', [])

...

	.factory('Documents', function( $resource ) {
		return $resource('http://localhost:3000/documents/:id', { id : '@_id' }, {
			'query' : { method : 'GET', params : { subject : '@subject' }, isArray : true },
			'update' : { method : 'PUT' }
		});
	})

...
 
angular.module('myLibraryApp')
	.controller('BookInfoController', function ($scope, $http, $state, $stateParams, Subjects, Documents){

...

		$scope.newDocument = function(){
			// Start timing now
			console.time('BookInfoController.newDocument.job.timespan');

			var bookData = $scope.bookInfo;
				
			// Because Google doesn't deliver all data, 
			// validations have to be applied.
			var di = {
				lib_code : ''
				,doc_type : 'book'
				,authors : bookData.volumeInfo.authors
				,publisher : bookData.volumeInfo.publisher.trim()
				,pages : bookData.volumeInfo.pageCount
				,publishing_date : bookData.volumeInfo.publishedDate
				,publishing_city : ''
				,isbn10 : bookData.volumeInfo.industryIdentifiers == undefined ? bookData.volumeInfo.industryIdentifiers[0].identifier : 0
				,isbn13 : bookData.volumeInfo.industryIdentifiers == undefined ? bookData.volumeInfo.industryIdentifiers[1].identifier : 0
				,description : bookData.volumeInfo.description
				,title : bookData.volumeInfo.title.trim()
				,subject : $scope.subject.name
			}

			var newDoc = new Documents.save(di);

			// transfer to selected subjects books list passing the name as parameter
			$state.go('documents.subject', { 'subject' : $scope.subject.name }, {reload: true, location: false});
			
			// Stop timer.
			console.timeEnd('BookInfoController.newDocument.job.timespan');
		}

...
 

Related Links

http://docs.mongodb.org/manual/data-modeling/

http://mongoosejs.com/docs/guide.html

Leave a comment