2017-04-19 103 views
0

我試圖以下列格式導出Mongodb實例db,但我無法得到它。導出mongodb失敗

文件夾結構

catering 
    -server 
    -server.js 
    -mongoclient.js 
    -package.json 

這是我的個人檔案

mongoclient.js

var MongoClient = require('mongodb').MongoClient; 
var _db; 
var exec = require("child_process").exec; 
var async = require('async'); 
var series = require('async/series'); 
var file = __dirname + '/server.js'; 


async.series([ 
    function(callback){ 
     MongoClient.connect("mongodb://localhost:27017/catering",     function(err, db) { 
     _db = db; 
     db.createCollection('posts'); 
     module.exports = {db:db}; 
     // callback(db + "11111"); 
     callback(null,123) 
    }); 
    }, 
    function(callback){ 
    exec('nodemon '+ file,{},function(err,res){ 
     if(err){ 
      callback(null,err) 
     }else{ 
      callback(null,res); 
     } 
    }) 
    } 
],function(err,res){ 
    console.log("===========res",res,err) 
}) 

Server.js

var express = require("express"); 
var app = express(); 
var fs = require('fs'); 
var path = require("path"); 
var db = require('./mongoclient.js'); 

app.listen(4000); 

app.get('/',function(req,res){ 
    console.log("00000000000000000000get",db);  
    res.sendFile(path.join(__dirname + '/../client/index.html')) 
}); 

的package.json

{ 
    "name": "catering", 
    "version": "1.0.0", 
    "description": "", 
    "main": "index.js", 
    "scripts": { 
    "start": "npm-run-all --parallel connect:mongo build:watch", 
    "build:watch": "webpack --watch", 
    "connect:mongo": "nodemon ./server/mongoclient.js", 
    "test": "echo \"Error: no test specified\" && exit 1" 
    }, 
} 
+0

檢查此鏈接了,這可能是有用的:http://stackoverflow.com/questions/17098855/node-js-和-mongodb-reusing-the-db-object –

+0

http://stackoverflow.com/questions/20315434/node-js-asynchronous-module-loading –

回答

0

我上的使用@Aagam鏈接上面的問題。以下是更新後的代碼

module.exports.init = function (callback) { 
    var server = new mongodb.Server("127.0.0.1", 27017, {}); 
    new mongodb.Db('catering', server, {w: 1}).open(function (error, client) { 
     module.exports.client = client; 
     if(client) 
     callback(client,undefined) 
     else 
     callback(undefined,error); 
    }); 
}; 

Server.js

db.init(function(res,err){console.log("----------data",res); console.log("----------------err",err)})