Elegant use of MongoDB instances from scratch

Source: Internet
Author: User

Basic connection

First, create Express project Testmon

Express Testmon

Second, streamline App.js

var express = Require ("Express"); var app = Express (); App.get (function(req, res) {     res.send (' Add one piece of data at a time ') ; }); var server = App.listen (,function() {    console.log ("Please visit in Browser: http://localhost : (");});

Three: Enter the engineering directory to install Mongoose and introduce dependencies:

NPM Install--save Mongoose

Iv. Modification of App.js

varExpress = Require ("Express");varApp =Express (); App.get (‘/‘,function(req, res) {Res.send (' Hello, tinyphp '); });varServer = App.listen (3000,function() {Console.log ("Please visit in Browser: http://localhost:3000");});//Introducing the Mongoose modulevarMongoose = require (' Mongoose '));//Create a database connectionvarDb=mongoose.connect (' Mongodb://localhost:27017/test ');//Check if the connection is successfulDb.connection.on ("Error",function(Error) {Console.log ("Database connection failed:" +( error);}); Db.connection.on ("Open",function(Error) {Console.log ("++++++ Database successfully ++++++");});/*****schema Use * * * **///define the Kitty propertyvarKittyschema =Mongoose. Schema ({name:string});//publish the schema as model, the first parameter is a collection namevarKittymodel = Mongoose.model (' Kitty ', Kittyschema);//create a kitty entity with modulevarKittyentity =NewKittymodel ({name: ' tinyphp99 ') });//Save DataKittyentity.save (function(err) {if(Err) {Console.log (err); } Else{Console.log (' successfully inserting data '); }});/************/

Open another CMD window, first query the data once, then restart the project, and then query the data discovery data successfully added

Separation and transformation

Let's convert it to a visit Http://localhost:3000/add automatically add data, ideas

Config.js Database configuration information

module.exports={    MongoDB:"Mongodb://localhost:27017/test"}

Mongoose.js Database Connection File

//Introducing the Mongoose modulevarMongoose = require (' Mongoose '));varConfig=require ('./config.js ')); Module.exports=function(){    //Create a database connectionvardb=Mongoose.connect (CONFIG.MONGODB);//Check if the connection is successfulDb.connection.on ("Error",function(Error) {Console.log ("Database connection failed:" +( error);}); Db.connection.on ("Open",function(Error) {Console.log ("++++++ Database successfully ++++++");}); Require (‘.. /models/kitty.model.js ');returnDB;}

Kitty.model.js export model for generating entities

var mongoose =require (' Mongoose '); /* ****schema Use * * * * */ // define the Kitty property var kittyschema = Mongoose. Schema ({    name:string  }); Mongoose.model (' Kitty ', Kittyschema);

App.js

var express = Require ("Express"); var mongoose = require ('./config/mongoose.js 'var db=Mongoose (); var app = Express (); var add=require ('./routes/add '); App.use ('/add ', add); var server = App.listen (,function() {    console.log ("Please visit in Browser:/http localhost:3000 ");});

Add.js Control Access once http://localhost:3000/add insert data once

varExpress = require (' Express ');varRouter =Express. Router ();varMongoose =require (' Mongoose '));varKittymodel=mongoose.model (' Kitty '));/*GET home page.*/Router.get (‘/‘,function(req, res, next) {Res.send (' Add another piece of data ');//publish the schema as model, the first parameter is a collection namevarKittymodel = Mongoose.model (' Kitty ');//create a kitty entity with modulevarKittyentity =NewKittymodel ({name: ' new ') });//Save DataKittyentity.save (function(err) {if(Err) {Console.log (err); } Else{Console.log (' successfully inserting data '); }});}); Module.exports= Router;

In the route because of the use of Kittymodel so introduced to the mongoose initialization, otherwise it will prompt the error "Schema hasn ' t been registered ...", you put the above in the order of the test more profound Oh ~

Warm tip: More testing, you may wish to use Db.table.drop () to remove the entire collection OH

Related articles:

Install Express and create a project

Windows Platform Installation MongoDB

Elegant use of MongoDB instances from scratch

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.