node操作MongoDB資料庫之插入

來源:互聯網
上載者:User

標籤:

在上一篇中我們介紹了MongoDB的安裝與配置,接下來的我們來看看在node中怎樣操作MongoDB資料庫。

在操作資料庫之前,首先應該像關係型資料庫一樣建個資料庫把。。。

啟動資料庫

利用命令提示字元:

1、在建立資料庫之前,我們應該啟動資料庫伺服器

mongod --dbpath d:\MongoDB\data

注意:不要關閉這個資料庫伺服器。。。不然資料庫就被關閉了

2、使用如下語句建立一個資料庫

use mydb

這樣mongodb會協助我們自動建立他們,當然這個時候資料庫還是空的。

3、檢驗資料庫是不是已經被建立

show dbs

你會在控制台看到剛才建立的mydb已經被建立出來了。

你也可以在上面提到的data檔案加下看到建立的結果。

上面關於MongoDB資料庫的操作建立完畢了。接下來就是對node的操作了。

構建node項目

在本機任意盤上建立一個空檔案夾,這裡我是用的IntelliJ IDEA,在IDE中建立一個node項目。

在開始寫代碼之前需要利用npm下載我們在node中使用到的mongodb模組,就好像是mysql的資料庫驅動程式一樣,這樣我們才可以串連資料庫。

在命令列視窗中cd到新建立的node項目。輸入如下代碼:


npm install mongodb

你會看到項目中多了一個node_modules檔案,這個檔案裡麵包含的就是mongodb模組了。

所有的都購建好了之後,我們就要開始具體的編碼工作了。。

串連資料庫

輸入如下代碼用於串連上面我們建立的mydb資料庫:

/** * Created with IntelliJ IDEA. * User: Administrator * Date: 15-6-4 * Time: 下午4:18 * To change this template use File | Settings | File Templates. */var mongo = require(‘mongodb‘);var host = ‘localhost‘;var port = 27017;var server = new mongo.Server(host,port,{auto_reconnect:true});var db = new mongo.Db(‘mydb‘,server,{salf:true});db.open(function(err,db){    if(err){        throw err;    }else {        console.log(‘成功串連資料庫‘);        db.close();    }});db.on(‘close‘,function(err,db){    if(err){        throw err;    }else{        console.log("成功關閉資料庫");    }});

運行代碼,你會在控制帶看到兩句輸出:

成功串連資料庫成功關閉資料庫

這樣monogdb資料庫就已經串連上來了,接下來再看看把一個資料插入資料庫。

插入資料庫

輸入如下代碼:

/** * Created with IntelliJ IDEA. * User: Administrator * Date: 15-6-4 * Time: 下午4:18 * To change this template use File | Settings | File Templates. */var mongo = require(‘mongodb‘);var host = ‘localhost‘;var port = 27017;       //    MongoDB資料庫預設的連接埠號碼var server = new mongo.Server(host,port,{auto_reconnect:true});var db = new mongo.Db(‘mydb‘,server,{salf:true});db.open(function(err,db){    if(err){        throw err;    }else {        db.collection(‘user‘,function(err,collection){            collection.insert({username:‘liwei‘,age:25,sex:‘male‘},function(err,docs){                console.log(docs);     //   輸出我們插入的內容                db.close();            });        });    }});db.on(‘close‘,function(err,db){    if(err){        throw err;    }else{        console.log("成功關閉資料庫");    }});

運行代碼,在控制你會看到我們插入的內容如下:

同樣在命令列我們也可以看到我們插入的資料:

 

 

node操作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.