[英]How to use connection file of mongo db in other files of node.js application
I have a file, connection.js that I want to use in another file. 我有一个要在另一个文件中使用的connection.js文件。 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. 例如,我还有一个名为item.js的文件,其中要将项目详细信息添加到数据库中。
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 item.js
In this file the addItem
function takes a JSON object which I want to store in the database. 在此文件中, addItem
函数采用一个JSON对象,该对象要存储在数据库中。 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
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);
而不是function(err, db)
使用回调MongoClient.connect(url, callback);
latter in your item.js just use the connection var 您item.js中的后者只需使用连接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
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.