mongodb - How to use connection file of mongo db in other files of node.js application -


i have file, connection.js want use in file. how can use file in file inserting , updating database. example have file named item.js in want add item details database.

var mongodb = require('mongodb');  module.exports = function() {      this.getconnection = function(callback) {          var mongoclient = mongodb.mongoclient;         var url = 'mongodb://localhost:27017/shoppingcart';          console.log(url);          mongoclient.connect(url, function(err, db) {              if (err) {                 console.log('unable connect mongodb server. error:', err);                 return;             } else {                 console.log('connection established to', url);                 return callback;             } //else          }); //mongoclient.connect      }; //connection  }; //constructor 

item.js

in file additem function takes json object want store in database. need connect database , insert result, don't understand how connect database.

i tried it's not working:

 /**   * shopping cart   * @author sunil hirole   * @date 15-july-2015   * e-commerce application purchasing items   */  var prompt = require('prompt'); var item = require('../models/itemarray.js'); var connection = require('../util/con.js');  /**    * item class model class   * contains additem,edititem,showitem,deleteitem functions   */  function item(){     this.id;     this.name;     this.price; }//item   /**   *additem function    **/  item.prototype.additem = function(result){ var connection = new connection(); var db = connection.getconnection(function(err,db){}); var collection = db.collection('itemsarray'); collection.insert([result], function(err, result) {     if (err) {         console.log(err);         return;         }      else {         return result;         } //close connection db.close();  });   return(result);   }//additem 

hello try exporting callback function in line have

module.exports = function(callback) {      var mongoclient = mongodb.mongoclient;     var url = 'mongodb://localhost:27017/shoppingcart';     mongoclient.connect(url, callback) 

instead of function(err, db) use callback mongoclient.connect(url, callback);

latter in item.js use connection var

var connection = require('../util/con.js');  // rest of file here  connection(function(err,db){     db.collection('itemsarray').     insert([result], function(err, result) {      if (err) {         console.log(err);        return;      }       else {         return result;      } //close connection }); 

Comments

Popular posts from this blog

qt - Using float or double for own QML classes -

Create Outlook appointment via C# .Net -

ios - Swift Array Resetting Itself -