Follow by Email

Tuesday, September 22, 2015

sample interface for inserting data into mongodb using node.js

1. Below is the npm module(mongodb) link which i used to create a basic interface for inserting
documents into mongodb collections using node.js

https://www.npmjs.com/package/mongodb

2. I have been using RoboMongo GUI for viewing into MongoDB Database.

Steps:

1. install node.js and mongodb 
2. create a new folder and access it thru terminal/Cmd
3. Now type npm init, it will ask you certain things and will create a package.json based on your input values.
4. mention the required dependencies for mongodb in package.json file.
5. Create a new file called index.js , and paste this below code
6. final step to run the node.js interface from the terminal type --> node index.js 

package.json

{
  "name": "mongoapp",
  "version": "1.0.0",
  "description": "new mongo",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "mongo"
  ],
  "author": "chandan",
  "license": "ISC",
   "dependencies": {
    "mongodb": "~2.0"
  },
}


index.js

var MongoClient = require('mongodb').MongoClient
  , assert = require('assert');
 
// Connection URL 
var url = 'mongodb://localhost:27017/mydb';
// Use connect method to connect to the Server 
MongoClient.connect(url, function(err, db) {
  assert.equal(null, err);
  console.log("Connected correctly to server");
  insertDocuments(db,logStuff);
});

function logStuff(result)
{
console.log(result);
}

var insertDocuments = function(db, callback) {
  // Get the documents collection 
  var collection = db.collection('documents');
  // Insert some documents 
  collection.insert([
    {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 document collection");
    callback(result);
  });
}