從零開始優雅的使用mongodb執行個體

來源:互聯網
上載者:User

標籤:...   function   ref   從零開始   集合   +++   images   參數   port   

基本串連

一、建立express工程testmon

express testmon

 

二、精簡app.js

var express = require("express");var app = express();app.get(‘/‘, function(req, res) {     res.send(‘訪問一次增加一條資料‘); });var server = app.listen(3000,function(){    console.log("請在瀏覽器訪問:http://localhost:3000");});

 

三:進入工程目錄安裝mongoose並引入依賴:

npm install --save mongoose

四、修改app.js

var express = require("express");var app = express();app.get(‘/‘, function(req, res) { res.send(‘Hello, tinyphp‘); });var server = app.listen(3000,function(){    console.log("請在瀏覽器訪問:http://localhost:3000");});//引入mongoose模組var mongoose = require(‘mongoose‘);//建立資料庫連接var db=mongoose.connect(‘mongodb://localhost:27017/test‘);//檢查是否串連成功db.connection.on("error",function(error){    console.log("資料庫連接失敗:"+error);});db.connection.on("open",function(error){    console.log("++++++資料庫連成功++++++");});/*****Schema使用*****///定義kitty屬性var kittySchema = mongoose.Schema({    name: String  });//將該Schema發布為Model,第一個參數為集合名var kittyModel = mongoose.model(‘kitty‘, kittySchema);//用module建立kitty實體var kittyEntity = new kittyModel({ name: ‘tinyphp99‘ });//儲存資料kittyEntity.save(function (err) {  if (err) {    console.log(err);  } else {    console.log(‘成功插入資料‘);  }});/************/

開啟另外一個cmd視窗,先查詢一次資料,然後重新啟動工程,再查詢一次資料探索資料成功添加上了

 

分離改造

下面我們把它改裝為一訪問http://localhost:3000/add就自動添加資料,思路

 

config.js 資料庫配置資訊

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

mongoose.js 資料庫連接檔案

//引入mongoose模組var mongoose = require(‘mongoose‘);var config=require(‘./config.js‘);module.exports=function(){    //建立資料庫連接var db=mongoose.connect(config.mongodb);//檢查是否串連成功db.connection.on("error",function(error){    console.log("資料庫連接失敗:"+error);});db.connection.on("open",function(error){    console.log("++++++資料庫連成功++++++");});require(‘../models/kitty.model.js‘);return db;}

kitty.model.js 匯出Model用於產生實體

var mongoose =require(‘mongoose‘);/*****Schema使用*****///定義kitty屬性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(3000,function(){    console.log("請在瀏覽器訪問:http://localhost:3000");});

add.js 控制訪問一次http://localhost:3000/add插入一次資料

var express = require(‘express‘);var router = express.Router();var mongoose =require(‘mongoose‘);var kittyModel=mongoose.model(‘kitty‘);/* GET home page. */router.get(‘/‘, function(req, res, next) {  res.send(‘又添加一條資料‘);//將該Schema發布為Model,第一個參數為集合名var kittyModel = mongoose.model(‘kitty‘);//用module建立kitty實體var kittyEntity = new kittyModel({ name: ‘new‘ });//儲存資料kittyEntity.save(function (err) {  if (err) {    console.log(err);  } else {    console.log(‘成功插入資料‘);  }});});module.exports = router;

路由裡因為用到kittyModel所以引入要在mongoose初始化後,不然會提示出錯“Schema hasn‘t been registered ...”, 自己把上面的順序調換測試下更深刻噢~

溫馨提示:測試多了,不妨使用db.table.drop() 把整個集合刪除掉噢

相關文章:

安裝express並建立工程

window平台安裝MongoDB

 

從零開始優雅的使用mongodb執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.