mongodb with nodejs

this is th code I am using inserting a document to 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);
});

but while running I am getting error

xports, require, module, __filename, __dirname) { var client = new Db('test', ^ ReferenceError: Db is not defined at Object. (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)

can you suggest me how to solve this problem

thanks in advance

Please import all the required modules, which you are using. Db is not defined points out that Db is defined in some other module or you have forgot to declare it.

You'll notice this exact code block posted in a number of different stackoverflow questions. The problem here is that this is a copy and pasted code block from mongodb's documentation, as is in fact the first example of a mongodb nodejs program.

https://npmjs.org/package/mongodb

You'll find this under "Introduction" as "A simple example of inserting a document."

It's clearly an incomplete example, but a lot of people are just trying it out to see if they've got everything installed correctly and immediately run into a wall.

Most people will have installed the mongodb driver, but will be missing something at the top like this:

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

I also fell into the copy-paste trap here and ran into another issue with the "assertEquals" method not existing. I've seen other people reference that function in other places on the web, but not really sure how it works.

In any case, to make it work for me, I required the assert module:

var assert = require('assert');

And then I replaced the assertEquals lines with something like this:

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

Note that you're going to run into an issue if you've run this a couple of times; it's going to count the number of things in that table, and there is going to be more than one.

You'll have to figure out how to get into mongo's CLI and remove them to get it to run successfully.

Try to install mongodb native driver

npm install mongodb