Express+mongodb step for ' win '

Source: Internet
Author: User
Tags findone install mongodb

1190000008830333

Prelude

What is Express?

Express is a minimalist, flexible Web application Development framework based on the node. JS platform that provides a range of powerful features to help you create a wide variety of web and mobile device applications.

Global Installation Express Scaffolding

$ npm install express-generator -g

Create an Express project

cd myapp$ npm install$ DEBUG=myapp npm start

MongoDB and Mongoose?

  • MongoDB is an object database, which is used to store data, and the stored data format is JSON.

  • Mongoose is an object model library that encapsulates MONGODB operations (such as add-and-scan), which is used to manipulate the data.

To install MongoDB:
Https://www.mongodb.com/download-center?jmp=nav

Install Mongoose:

$ npm install mongoose --save
First, connect MongoDB

Create a new/lib/mongo.js under the project root directory

var mongoose = require("mongoose");var db = mongoose.connect(‘mongodb://localhost:27017/myblog‘);module.exports = db

The database to connect to is MyBlog

Second, Schema

A database model skeleton, which is stored as a file, does not have direct access to the database, does not have the ability to operate the database, but is only a representation of the database model in the program fragment, which can be described as the data attribute model (the traditional table structure) or the model skeleton of "set".

Create a new user schema

Create a new/models/users.js under the project root directory

var Mongoose =Require"Mongoose");var db =Require‘.. /lib/mongo ');A user modelvar Userschema = new Mongoose. Schema ({username: {type:string}, Password: {type: string}, Avatar: {type: string}, Age: {type:number, default:0}, Description: {type: string}, email : {type: string}, GitHub: {type: string}, Time: {Type:date, default:Date.now}); //create Modelvar Usermodel = Db.model ( "user ", Userschema); module.exports = Usermodel          
  • User: The collection name in the database, when we add data to it, if the user already exists, it is saved to its directory, and if it does not exist, the user collection is created, and then the data is saved.

  • With the model, we also have the operating database of the Golden Key, you can use model for the specific operation of the increase and deletion check.

Entity

Entities created by model use the Save method to save data, both model and entity have operations that affect the database, but the model is more operational than entity.

var UserEntity = new UserModel({    name : "hzzly",    age  : 21,    email: "[email protected]", github: ‘https://github.com/hzzly‘});UserEntity.save(function(error,doc){ if(error){ console.log("error :" + error); }else{ console.log(doc); }});
third, the curd of the encapsulation database
  • Create a new api.js under Lib file

  • The use of promise encapsulation of the database operation, avoid callback to hell, so that the code can be better read and maintenance.

var Usermodel =Require‘.. /models/users ');Module.exports = {/** * Add Data * @param {[type]} data needs to be saved to the object */SaveReturnNew Promise ((resolve, reject) = {Model.create (Saved object, callback) Usermodel.create (data, (Error, doc) + = {if (Error) {Reject (Error)}else{Resolve (DOC)})})}, find (data={}, fields=NULL, options={}) {ReturnNew Promise ((resolve, reject) = {Model.find (Find all data if empty), attribute filter object [optional parameter], options[optional parameter], callback) usermodel.find (data, fields, options, ( Error, doc) = = {if (Error) {Reject (Error)}else{Resolve (DOC)})})}, FindOne (data) {ReturnNew Promise ((resolve, reject) = {Model.findone (object to find, callback) Usermodel.findone (data, (Error, doc) + = {if (Error) {Reject (Error)}else{Resolve (DOC)})})}, FindByID (data) {ReturnNew Promise ((resolve, reject) = {Model.findbyid (ID object to look for, callback) Usermodel.findbyid (data, (Error, doc) + = {if (Error) {Reject (Error)}else{Resolve (DOC)})}) }, update (conditions, update) { return new Promise ((resolve, reject) = { //model.update (query condition, update object, Callback) Usermodel.update (conditions, update, (Error, doc) = { if (error) {Reject (Error)}else{Resolve (DOC) }})}, remove (conditions) { return new Promise ((resolve, reject) = { //model.update (query condition, callback) use Rmodel.remove (conditions, (error, doc) = { if (error) {Reject (Error)}else{Resolve (DOC)}})}}} 
Iv. Use of

Use in/routers/index.js

var API =Require‘.. /lib/api '); Router.post ('/login ',function(req, res, next) {var user = {username:req.body.username, password:req.body.password}; Api.findone (user). Then (result = =Console.log (Result)})}) Router.post ('/sign_up ',function(req, res, next) {var user = {Username:req.body.username, Password:req.body.password, email:req.body.email}; Api.save (user). Then (result = =Console.log (Result)})}) Router.get ('/user_list ',function(req, res, next) {Returns all user Api.find ({}). then (result = =Console.log (Result)})Returns all records that contain only one key value, name, age, Api.find ({},{name:1, Age:1, _id:0}). Then (result = {console.log (Result)}) //returns all data with age greater than 18 Api.find ({18}). then (result = = {console.log (Result)}) //returns 20 data api.find ({},null,{limit:20} ). Then (result = {console.log (Result)}) //query all data, and returns the data in descending order of age Api.find ({},null,{sort:{age:-< span class= "Hljs-number" >1}}) //1 is ascending,-1 is descending. Then (result = = {console.log (Result)})   

Express+mongodb step to ' win '

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.