Node.js 带nodejs的mongodb

Node.js 带nodejs的mongodb,node.js,mongodb,Node.js,Mongodb,这是我用来向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)

这是我用来向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,require,module,_文件名,_目录名){var client=new Db('test', ^ ReferenceError:未定义数据库 在对象上。(C:\Users\Basic node\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)
你能建议我如何解决这个问题吗


提前感谢

请导入您正在使用的所有必需模块。
Db未定义
指出
Db
已在其他模块中定义,或者您忘记声明。

尝试安装mongodb本机驱动程序

npm install mongodb

您会在许多不同的stackoverflow问题中注意到这个确切的代码块。这里的问题是,这是mongodb文档中的复制和粘贴的代码块,事实上这是mongodb nodejs程序的第一个示例

您可以在“简介”中找到“插入文档的简单示例”

这显然是一个不完整的例子,但很多人只是尝试一下,看看他们是否已经正确安装了所有东西,并立即撞到墙上

大多数人都已经安装了mongodb驱动程序,但是上面缺少了如下内容:

var mongodb = require('mongodb');
var Db = mongodb.Db;
var Server = mongodb.Server;
          assert.equal(1, count, "Unexpected result");
我在这里也陷入了复制粘贴陷阱,遇到了另一个“assertEquals”方法不存在的问题。我曾看到其他人在web上的其他地方引用该功能,但并不确定它是如何工作的

在任何情况下,为了让它为我工作,我需要assert模块:

var assert = require('assert');
然后我将assertEquals行替换为如下内容:

var mongodb = require('mongodb');
var Db = mongodb.Db;
var Server = mongodb.Server;
          assert.equal(1, count, "Unexpected result");
请注意,如果您运行了几次,您将遇到一个问题;它将计算该表中的内容数量,并且将有不止一个


您必须弄清楚如何进入mongo的CLI并将其删除,才能使其成功运行。

问题非常清楚。“Db”变量没有定义。如果您想要正确的答案,您必须在最初声明Db(可能还有服务器)的位置发布代码对象。您在哪里定义Db。可能您错过了导入具有Db的模块。我忘记导入mongodb模块。我知道它工作正常。谢谢回复