[英]How to use connection file of mongo db in other files of node.js application
我有一個要在另一個文件中使用的connection.js文件。 如何在另一個文件中使用此文件來插入和更新數據庫。 例如,我還有一個名為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
在此文件中, addItem
函數采用一個JSON對象,該對象要存儲在數據庫中。 為此,我需要連接到數據庫,然后插入結果,但是我不知道如何連接到數據庫。
我試過了,但是沒有用:
/**
* 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
你好,只是嘗試在您的行中導出回調函數
module.exports = function(callback) {
var MongoClient = mongodb.MongoClient;
var url = 'mongodb://localhost:27017/ShoppingCart';
MongoClient.connect(url, callback)
而不是function(err, db)
使用回調MongoClient.connect(url, callback);
您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.