繁体   English   中英

如何在node.js应用程序的其他文件中使用mongo db的连接文件

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM