国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

使用Nodejs連接mongodb數據庫的實現代碼

2024-05-06 15:12:35
字體:
來源:轉載
供稿:網友

一個簡單的nodejs連接mongodb示例,來自 mongodb官方示例

1. 創建package.json

首先,創建我們的工程目錄connect-mongodb,并作為我們的當前目錄

mkdir connect-mongodbcd connect-mongodb

輸入npm init命令創建package.json

npm init

然后,安裝mongodb的nodejs版本driver

npm install mongodb --save

mongodb驅動包將會安裝到當前目錄下的node_modules中

2. 啟動MongoDB服務器

安裝MongoDB并啟動MongoDB數據庫服務,可參考我之前的文章,或者MongoDB官方文檔

3. 連接MongoDB

創建一個app.js文件,并添加以下代碼來連接服務器地址為192.168.0.243,mongodb端口為27017上名稱為myNewDatabase的數據庫

var MongoClient = require('mongodb').MongoClient,  assert = require('assert');// Connection URLvar url = 'mongodb://192.168.0.243:27017/myNewDatabase';MongoClient.connect(url,function(err,db){  assert.equal(null,err);  console.log("Connection successfully to server");  db.close();});

在命令行輸入以下命令運行app.js

node app.js

4. 插入文檔

在app.js中添加以下代碼,使用insertMany方法添加3個文檔到documents集合中

var insertDocuments = function(db, callback){  // get ths documents collection  var collection = db.collection('documents');  // insert some documents  collection.insertMany([    {a:1},{a:2},{a:3}  ],function(err,result){    assert.equal(err,null);    assert.equal(3,result.result.n);    assert.equal(3,result.ops.length);    console.log("Inserted 3 documents into the collection");    callback(result);  });};

insert命令返回一個包含以下屬性的對象:

result MongoDB返回的文檔結果 ops 添加了_id字段的文檔 connection 執行插入操作所使用的connection

在app.js更新以下代碼調用insertDocuments方法

var MongoClient = require('mongodb').MongoClient , assert = require('assert');// Connection URLvar url = 'mongodb://localhost:27017/myproject';// Use connect method to connect to the serverMongoClient.connect(url, function(err, db) { assert.equal(null, err); console.log("Connected successfully to server"); insertDocuments(db, function() {  db.close(); });});

在命令行中使用node app.js運行

5. 查詢所有文檔

添加findDocuments函數

var findDocuments = function(db,callback){  // get the documents collection  var collection = db.collection('documents');  // find some documents  collection.find({}).toArray(function(err,docs){    assert.equal(err,null);    console.log("Found the following records");    console.log(docs);    callback(docs);  });};

findDocuments函數查詢了所有'documents'集合中所有的文檔,將此函數添加到MongoClient.connect的回調函數中

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 宿州市| 江西省| 长汀县| 莱西市| 茌平县| 玉环县| 莱州市| 屏边| 芦溪县| 加查县| 永寿县| 田林县| 荥经县| 碌曲县| 依兰县| 安庆市| 高邑县| 梧州市| 五寨县| 揭西县| 山东省| 林口县| 东平县| 乌兰县| 兴隆县| 西乌珠穆沁旗| 措美县| 焉耆| 南城县| 宾阳县| 金华市| 讷河市| 托克逊县| 平武县| 呼图壁县| 自贡市| 太谷县| 永兴县| 右玉县| 锡林浩特市| 华坪县|