In the previous section, we talked about the Library management system login, I believe that we have a jade template and angular JS also have a understanding, today we look at a book information input. Here we are going to use the NoSQL database, which is used by MongoDB in this blog post. Ok. Mongo DB Installation I don't have to say much, then the node. JS Platform uses mongodb what extension package we use, I think it is mongoose more appropriate, encapsulated a lot of methods for MongoDB, easy to use.
First, let's take a look at the design bookinfo.js of the book model.
var mongoose = require(‘mongoose‘);
var Schema = mongoose.Schema;
var bookSchema = new Schema({
_id: Schema.Types.ObjectId,
Title: { type: String, index: true, required: true },
ISBN: { type: String, required: true , unique: true },
Author: { type: String },
Price: { type: Number, min: 0.1, max: 99999 },
Press: { type: String, required: true },
PressDate: { type: Date, default: Date.now },
Description: { type: String, required: true },
Image: { type: Schema.ObjectId }
}, {
strict: true,
toObject: {
virtuals: true
},
toJSON: {
virtuals: true
}
});
bookSchema.virtual(‘bookFullName‘).get(function () {
return this.title + ‘(‘ + (this.author? this.author:‘‘) + ‘)‘;
});
bookSchema.methods.saveBookInfo = function (callback) {
this._id = new mongoose.Types.ObjectId;
this.save(callback);
}
bookSchema.set(‘collection‘, ‘books‘);
var bookModel = mongoose.model("books", bookSchema);
exports.bookModel = bookModel;
First in the code we see a reference to the Mongoose extension package, which we can refer to in vs.
650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/82/E0/wKioL1djlrPheRaaAAAq_nNXgrQ394.png "title=" 1.png " alt= "Wkiol1djlrpheraaaaaq_nnxgrq394.png"/>
Click Install New NPM Packages
650) this.width=650; "Src=" Http://s1.51cto.com/wyfs02/M01/82/DF/wKioL1djhzODSy7mAACrbybCZU8285.png-wh_500x0-wm_3 -wmp_4-s_3990941219.png "title=" 2.png "alt=" Wkiol1djhzodsy7maacrbybczu8285.png-wh_50 "/>
Search for Mongoose, then click Install package or you can use the command line.
OK, at this point we require (' mongoose ') to load the Mongoose module. Then we define a bookschema, define some fields, type is its types, index supports indexes, required can be empty, and SQL Server-like IS-not null,unique are non-repeating constraints. Default defaults,
Objectid is the unique identifier for this piece of data, similar to SQL Server's primary key, formatted like a GUID. Here we find that the image field is a objectid, indicating that this is an externally unique identifier, similar to the foreign key of SQL Server. Next is strict:true, which means that the fields we define must be stored in MongoDB, and fields not defined by the schema are not stored. After the Ok,schema is defined, we define a virtual field for Bookschema, which is fictitious, meaning that the virtual field can be included in the returned results when the query returns. But the field itself is not in the MongoDB schema.
In addition, the above Tojson and Toobject are for this virtual field, and if False, the virtual field will not be included in either the return JSON or object.
Next we define the schema Method,savebookinfo, first the primary key value generation, then the Save method, the Save method is provided by Mongoose, Mongoose provides a series of additions and deletions to check the method, single batch support, very convenient.
Finally we set the name of the collection, define the model, and expose the Bookmodel module.
OK, here, the definition of the schema is finished, next we will provide the rest API to the client page, first link MongoDB, the code is as follows
#!/usr/bin/env node
var debug = require(‘debug‘)(‘ChinaBook‘);
var mongoose = require(‘mongoose‘);
initMongoose();
var app = require(‘../app‘);
app.set(‘port‘, process.env.PORT || 3000);
var server = app.listen(app.get(‘port‘), function() {
debug(‘Express server listening on port ‘ + server.address().port);
});
function initMongoose(){
mongoose.connect(‘localhost:27017/ChinaBook‘,function(err, db){
if (err) {
console.log(‘Unable to connect to the mongoDB server. Error:‘, err);
} else {
console.log(‘Connection established to‘, ‘localhost:27017/ChinaBook‘);
}
});
}
Initmongoose is the connection using the Mongoose API to connect MongoDB, connected, and then into our controller code bookmng.js.
var bookSchemas = require(‘../model/bookinfo.js‘);
var bookMsgRes = require(‘../framework/message/book_msg.js‘);
var validator = require(‘validator‘);
var mongoose = require(‘mongoose‘);
var bookModel = bookSchemas.bookModel;
exports.bookSave = function (req, res) {
if (validator.isNull(req.body.Title)) {
res.json(bookMsgRes.buildJsonErrorRes(‘BookTitleEmpty‘));
return;
}
if (!validator.isISBN(req.body.ISBN)) {
res.json(bookMsgRes.buildJsonErrorRes(‘ISBNInCorrect‘));
return;
}
if (!validator.isFloat(req.body.Price, { min: 0.01, max: 999999 })) {
res.json(bookMsgRes.buildJsonErrorRes(‘PriceInCorrect‘));
return;
}
if (validator.isNull(req.body.Press)) {
res.json(bookMsgRes.buildJsonErrorRes(‘PressEmpty‘));
return;
}
if (validator.isNull(req.body.Description)) {
res.json(bookMsgRes.buildJsonErrorRes(‘DescriptionEmpty‘));
return;
}
var bookEntity = new bookModel(req.body);
bookEntity.saveBookInfo(function (error, doc) {
if (error) {
res.json({ isSuc: false, msg: error.message });
} else {
res.json({ isSuc: true });
}
});
}
Here we introduce the schema file just defined to get the public Bookmodel module. We expose a Booksave method with parameters of Req,res, which we can see from this name is HTTP request and HTTP response. The method first validates the incoming field, verifies the validator expansion pack we use, or installs it as if it were a mongoose. Validator has many verification methods
650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/82/E0/wKiom1djj2WSYtS9AAD8Lbqao_s213.png "title=" 1.png " alt= "Wkiom1djj2wsyts9aad8lbqao_s213.png"/>
For more information, see: Https://www.npmjs.com/package/validator
OK, after validation, we directly convert the JSON data passed by the client into model, where the client's field and server schema are the same, there is no problem, you want to deserialize. Finally we call Boomodel's Savebookinfo method and end. Note here that if the post is submitted, you need to use req.body value, if it is get?xx=xxx, is req.query, if it is get/:id, then the value is req.params.id. At this point, our controller is finished, so we are now publicly known as the rest API.
var router = express.Router();
router.post(‘/book‘, bookRoutes.bookSave);
Then the client only needs to call/book.
Look at the client's page code and JS.
#book_typeIn(ng-controller=‘bookTypeInCtrl‘)
label(style=‘font-size:17px‘) Book Info:
hr.panel-line
form(name=‘bookForm‘)
.row.row-middle-height
.col-md-12
.col-md-1
label Title:
.col-md-5
input.form-control(name=‘title‘ type=‘text‘ maxlength=‘50‘ placeholder=‘Book name‘ ng-model=‘Book.Title‘ required)
.col-md-6
p.error-message(ng-show=‘submitted && bookForm.title.$error.required‘) Title can‘t be empty.
.row.row-margin.row-middle-height
.col-md-12
.col-md-1
label ISBN:
.col-md-5
input.form-control(name=‘ISBN‘ type=‘text‘ ng-model=‘Book.ISBN‘ maxlength =‘30‘ required)
.col-md-6
p.error-message(ng-show=‘submitted && bookForm.ISBN.$error.required‘) ISBN can‘t be empty.
.row.row-margin.row-middle-height
.col-md-12
.col-md-1
label Author:
.col-md-5
input.form-control(type=‘text‘ maxlength =‘30‘ ng-model=‘Book.Author‘)
.row.row-margin.row-middle-height
.col-md-12
.col-md-1
label Price:
.col-md-5
input.form-control.tooltip-show(name=‘price‘ type=‘text‘ maxlength=‘10‘ ng-model=‘Book.Price‘ data-toggle=‘tooltip‘ data-placement=‘top‘ ng-pattern=‘/^[0-9]+(.[0-9]{2})?$/‘ title=‘Two decimal places‘)
.col-md-6
p.error-message(ng-show=‘submitted && bookForm.price.$error.pattern‘) Price is incorrect.
.row.row-margin.row-middle-height
.col-md-12
.col-md-1
label Press:
.col-md-5
input.form-control(name=‘press‘ type=‘text‘ maxlength=‘50‘ ng-model=‘Book.Press‘ required)
.col-md-6
p.error-message(ng-show=‘submitted && bookForm.press.$error.required‘) Press can‘t be empty.
.row.row-margin.row-middle-height
.col-md-12
.col-md-1
label PressDate:
.col-md-5
kendo-date-picker(name=‘pressDate‘ ng-model=‘Book.PressDate‘ k-format=‘yyyy-MM-dd‘ onkeydown=‘return false;‘ required)
.col-md-6
p.error-message(ng-show=‘submitted && bookForm.pressDate.$error.required‘) PressDate can‘t be empty.
.row.row-margin.row-middle-height
.col-md-12
.col-md-1
label Description:
.col-md-5
input.form-control(name=‘description‘ type=‘text‘ maxlength=‘200‘ ng-model=‘Book.Description‘ required)
.col-md-6
p.error-message(ng-show=‘submitted && bookForm.description.$error.required‘) Description can‘t be empty.
.row-margin
button.k-button.k-primary.btn-width-70(type=‘button‘ ng-click=‘bookInfoSave()‘) Save
button.k-button.k-primary.btn-width-70(type=‘button‘ ng-click=‘bookInfoReset()‘ style=‘margin-left:10px‘) Reset
block scripts
script(type=‘text/javascript‘ src=‘/javascripts/local/book/bookTypeIn.js‘)
A very simple page, using the Kendo DatePicker control, angularjs binding, with a book object binding, angular number and non-empty, regular expression validation, very simple, not much to say, look at JS.
var appModule = angular.module(‘bookTypeInModule‘, ["kendo.directives"]);
appModule.config(function ($locationProvider) {
$locationProvider.html5Mode(true);
});
appModule.controller(‘bookTypeInCtrl‘, function ($scope, $http, $location) {
angular.element(‘.tooltip-show‘).tooltip(‘show‘);
Messenger.options = {
extraClasses: ‘messenger-fixed messenger-on-top messenger-on-center‘,
theme: ‘flat‘
}
var now = new Date();
$scope.Book = {};
$scope.bookInfoSave = function () {
$scope.submitted = true;
if (!$scope.bookForm.$valid) {
return;
}
$http({
method: "post",
url: "/book",
headers: { ‘Content-Type‘: ‘application/json‘ },
data: $scope.Book
}).success(function (data) {
if (data.isSuc) {
$scope.bookInfoReset();
$scope.showMsg(‘success‘, ‘Saved successfully!‘);
}
else {
$scope.showMsg(‘error‘, data.msg);
}
});
}
$scope.bookInfoReset = function () {
$scope.Book = {};
$scope.submitted = false;
}
$scope.showMsg = function (type, msg) {
Messenger().post({
message: msg,
type: type,
hideAfter: 2,
showCloseButton: true
});
}
$scope.onError = function (error) {
$scope.UploadError = error;
}
});
angular.element(‘#book_typeIn‘).data(‘$injector‘, ‘‘);
angular.bootstrap(angular.element(‘#book_typeIn‘), [‘bookTypeInModule‘]);
Pop-up message we use Messager, at the time of saving, first check whether the client check has passed, passed, directly to the book object post to rest Api/book,ok, so that the code is complete. Note the last sentence, we all know that Angularjs only a launch portal, where I have a menu every point, will load a new page, so if the previous page has been injected into the launch page, we will set it as the start page will be error, so we first set the page injection to empty, Then set the page as the startup page without an error.
Finally, let's look at the results of the operation.
650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/82/E0/wKioL1djlujD-9npAABwFUqn8u4998.png "title=" 1.png " alt= "Wkiol1djlujd-9npaabwfuqn8u4998.png"/>
Kendo control is also very nice, very many sets of skin, the verification effect is as follows
650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/82/E1/wKiom1djlJDj42dsAABKvwwI76Q666.png "title=" 2.png " alt= "Wkiom1djljdj42dsaabkvwwi76q666.png"/>
More exciting, please see the next section to share. Alas, the soft pass only give me 8k, how to do, but also continue to work hard.
This article is from the "Technology Creation value" blog, please be sure to keep this source http://leelei.blog.51cto.com/856755/1790261
node. js closest Combat (ii) Book Management system (book information Entry)