Reputation: 239
I have a file, connection.js that I want to use in another file. How can I use this file in another file for inserting and updating a database. For example I have another file named item.js in which I want to add the item details into the 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 to connect to the mongoDB server. Error:', err);
return;
} else {
console.log('Connection established to', url);
return callback;
} //else
}); //MongoClient.connect
}; //Connection
}; //constructor
item.js
In this file the addItem
function takes a JSON object which I want to store in the database. For that I need to connect to the database and then insert the result, but I don't understand how to connect to the database.
I tried this but it's not working:
/**
* Shopping Cart
* @author Sunil Hirole
* @Date 15-july-2015
* This is an e-commerce application for purchasing items
*/
var prompt = require('prompt');
var item = require('../models/itemArray.js');
var Connection = require('../util/con.js');
/**
* Item class is a model class
* It 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
Upvotes: 3
Views: 6048
Reputation: 560
hello just try exporting the callback function in your line you 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 the callback MongoClient.connect(url, callback);
latter in your item.js just use the connection var
var connection = require('../util/con.js');
// the rest of the 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
});
Upvotes: 4