2013-03-11 75 views
-2

這是我使用插入文件到mongodb的第th個代碼。與nodejs的mongodb

 var client = new Db('test', new Server("127.0.0.1", 27017, {}), {w: 1}), 
     test = function (err, collection) { 
     collection.insert({a:2}, function(err, docs) { 

     collection.count(function(err, count) { 
      test.assertEquals(1, count); 
     }); 

     // Locate all the entries using find 
     collection.find().toArray(function(err, results) { 
      test.assertEquals(1, results.length); 
      test.assertTrue(results[0].a === 2); 

      // Let's close the db 
      client.close(); 
     }); 
     }); 
    }; 

client.open(function(err, p_client) { 
    client.collection('test_insert', test); 
}); 

,但在運行我得到錯誤

xports,要求,模塊,__filename,__dirname){VAR的客戶=新的DB( '測試', ^ 的ReferenceError:DB是沒有定義 在。對象(C:\用戶\基本節點\ cheerio \ mongonode.js:1:81

at Module._compile (module.js:449:26) 
at Object.Module._extensions..js (module.js:467:10) 
at Module.load (module.js:356:32) 
at Function.Module._load (module.js:312:12) 
at Module.runMain (module.js:492:10) 
at process.startup.processNextTick.process._tickCallback (node.js:244:9) 

你能建議我該如何解決這個問題

在此先感謝

+2

問題非常明確。 'Db'變量沒有定義。如果你想得到一個正確的答案,你必須在最初聲明你的Db(可能是服務器)對象的地方發佈代碼。 – 2013-03-11 07:05:35

+0

你在哪裏定義Db。也許你錯過了導入有Db的模塊。 – user568109 2013-03-11 11:39:10

+0

我忘了導入mongodb模塊。知道它工作正常。感謝您的回覆 – Ramesh 2013-03-11 12:23:19

回答

4

請導入所需的所有模塊,您正在使用。 Db is not defined指出Db是在其他某個模塊中定義的,或者您忘記聲明它。

0

嘗試安裝MongoDB的本地驅動程序

npm install mongodb 
3

你會發現張貼在許多不同的計算器問題,這個確切的代碼塊。這裏的問題在於,這是來自mongodb文檔的複製和粘貼代碼塊,實際上是mongodb nodejs程序的第一個示例。

https://npmjs.org/package/mongodb

你會發現這個在「導言」爲「插入文檔的一個簡單的例子。」

這顯然是一個不完整的例子,但很多人只是試圖看看他們是否已經正確安裝了所有東西,並立即撞上了牆壁。

大多數人都已經安裝了MongoDB的驅動程序,但在頂部這樣會失去了一些東西:

var mongodb = require('mongodb'); 
var Db = mongodb.Db; 
var Server = mongodb.Server; 

我也陷入了複製粘貼的陷阱在這裏跑進另一個問題用「的assertEquals 「方法不存在。我見過其他人在網絡上的其他地方引用該功能,但不確定它是如何工作的。

在任何情況下,使其爲我工作,我需要的斷言模塊:

var assert = require('assert'); 

然後我換成在斷言線,是這樣的:

  assert.equal(1, count, "Unexpected result"); 

請注意,您如果你已經運行了幾次,它將會遇到問題;它將計算該表中的事物數量,並且將會有多個。

您必須弄清楚如何進入mongo的CLI並刪除它們才能讓它成功運行。