Node.js開發 ---- 建立並串連資料庫mongodb

來源:互聯網
上載者:User

標籤:express   replace   localhost   att   串連數   flow   http   XML   tle   

1.MongoDB下載安裝E:\MongoDB

 

2.建立資料庫檔案的存放位置 E:\MongoDB\data\db

 

 

3.啟動mongodb服務

 

 

庫操作
  建立資料庫:第一步:use 建立資料庫名;第二步:進行此庫相關的操作;如果不進行第二步,該資料庫不會被建立
  查看資料庫:show dbs;
  建立表:db.createCollection(‘要建立的表名‘);
  查看當前資料庫下表: show collections;
  刪除當前資料庫指定表:db.表名.drop();
  刪除當前資料庫:db.dropDatabase();

---------------------------------------------------------------我是分割線------------------------------------------------------

 

下面寫一個簡單的demo

1.express建立E:\test   項目

不會點這

 

2.建立資料庫

E:\MongoDB\bin 啟動 mongo.exe

輸入

use text  \建立一個叫text的資料庫
db.createCollection(“users”) \建立一個集合
db.users.insert({“name”:“admin”,“password”:“111”}) \給users集合添加一個文檔。
db.users.find() \查詢你添加的文檔

 

 

3.項目串連資料庫

在項目根目錄下建立一個的檔案夾 database ,然後在建立一個db.js    E:\test \ database\db.js

 

[html] view plain copy  
  1. var mongoose = require(‘mongoose‘);  
  2. var db = mongoose.connect(‘mongodb://localhost/text‘);//;串連資料庫  
  3. var Schema = mongoose.Schema;   //  建立模型  
  4. var userScheMa = new Schema({  
  5.     name: String,  
  6.     password: String  
  7. }); //  定義了一個新的模型,但是此模式還未和users集合有關聯  
  8. exports.user = db.model(‘users‘, userScheMa); //  與users集合關聯  

 

 


4.views檔案夾建立視圖檔案

 

5.路由的控制
在routes檔案中的index.js

 

6.啟動node伺服器 

在http://localhost:3000/查看

 

 

 

 

demo檔案:https://github.com/MMMsCheng/nodedemoLogin

 

Node.js開發 ---- 建立並串連資料庫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.