第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在NodeJS應用程序和模塊之間正確重用到MongoDB的連接

如何在NodeJS應用程序和模塊之間正確重用到MongoDB的連接

MYYA 2019-07-09 12:41:41
如何在NodeJS應用程序和模塊之間正確重用到MongoDB的連接我一直在閱讀,但仍然困惑于如何在整個NodeJS應用程序之間共享相同的數據庫(MongoDB)連接。據我所知,當應用程序在模塊之間啟動和重用時,連接應該是打開的。我目前認為最好的方法是server.js(啟動時的主文件)連接到數據庫,并創(chuàng)建傳遞給模塊的對象變量。連接后,模塊將根據需要使用此變量,此連接將保持打開狀態(tài)。例如:    var MongoClient = require('mongodb').MongoClient;     var mongo = {}; // this is passed to modules and code     MongoClient.connect("mongodb://localhost:27017/marankings", function(err, db) {         if (!err) {             console.log("We are connected");             // these tables will be passed to modules as part of mongo object             mongo.dbUsers = db.collection("users");             mongo.dbDisciplines = db.collection("disciplines");             console.log("aaa " + users.getAll()); // displays object and this can be used from inside modules         } else             console.log(err);     });     var users = new(require("./models/user"))(app, mongo);     console.log("bbb " + users.getAll()); // not connected at the very first time so displays undefined然后是另一個模塊models/user看起來是這樣的:Users = function(app, mongo) {Users.prototype.addUser = function() {     console.log("add user");}Users.prototype.getAll = function() {     return "all users " + mongo.dbUsers;     }}module.exports = Users;現在我有可怕的感覺,這是錯誤的,所以這種方法是否有明顯的問題,如果是的話,如何使它更好?
查看完整描述

3 回答

?
一只斗牛犬

TA貢獻1784條經驗 獲得超2個贊

我一直在閱讀,但仍然困惑于如何在整個NodeJS應用程序之間共享相同的數據庫(MongoDB)連接。據我所知,當應用程序在模塊之間啟動和重用時,連接應該是打開的。我目前認為最好的方法是server.js(啟動時的主文件)連接到數據庫,并創(chuàng)建傳遞給模塊的對象變量。連接后,模塊將根據需要使用此變量,此連接將保持打開狀態(tài)。例如:

    var MongoClient = require('mongodb').MongoClient;
    var mongo = {}; // this is passed to modules and code

    MongoClient.connect("mongodb://localhost:27017/marankings", function(err, db) {
        if (!err) {
            console.log("We are connected");

            // these tables will be passed to modules as part of mongo object
            mongo.dbUsers = db.collection("users");
            mongo.dbDisciplines = db.collection("disciplines");

            console.log("aaa " + users.getAll()); // displays object and this can be used from inside modules

        } else
            console.log(err);
    });

    var users = new(require("./models/user"))(app, mongo);
    console.log("bbb " + users.getAll()); // not connected at the very first time so displays undefined

然后是另一個模塊models/user看起來是這樣的:

Users = function(app, mongo) {Users.prototype.addUser = function() {
    console.log("add user");}Users.prototype.getAll = function() {

    return "all users " + mongo.dbUsers;

    }}module.exports = Users;

現在我有可怕的感覺,這是錯誤的,所以這種方法是否有明顯的問題,如果是的話,如何使它更好?


查看完整回答
反對 回復 2019-07-09
?
ABOUTYOU

TA貢獻1812條經驗 獲得超5個贊

您可以創(chuàng)建一個mongoUtil.js模塊,該模塊具有連接到mongo和返回mongo db實例的功能:

const MongoClient = require( 'mongodb' ).MongoClient;const url = "mongodb://localhost:27017";var _db;module.exports = {

  connectToServer: function( callback ) {
    MongoClient.connect( url,  { useNewUrlParser: true }, function( err, client ) {
      _db  = client.db('test_db');
      return callback( err );
    } );
  },

  getDb: function() {
    return _db;
  }};

要使用它,你可以在你的app.js:

var mongoUtil = require( 'mongoUtil' );mongoUtil.connectToServer( function( err, client ) {
  if (err) console.log(err);
  // start the rest of your app here} );

然后,當你需要訪問其他地方的蒙戈時,比如在另一個地方.js文件,您可以這樣做:

var mongoUtil = require( 'mongoUtil' );var db = mongoUtil.getDb();db.collection( 'users' ).find();

這是因為在節(jié)點中,當模塊是require,它們只加載一次/來源一次,因此您將只得到一個_dbmongoUtil.getDb()將始終返回相同的實例。

注意,代碼沒有測試。


查看完整回答
反對 回復 2019-07-09
?
慕容708150

TA貢獻1831條經驗 獲得超4個贊

以下是我如何使用當代語法,基于圍棋奧列格的例子。我的是測試和功能。

我在代碼中添加了一些注釋。

./db/monGodb.js

 const MongoClient = require('mongodb').MongoClient
 const uri = 'mongodb://user:password@localhost:27017/dbName'
 let _db const connectDB = async (callback) => {
     try {
         MongoClient.connect(uri, (err, db) => {
             _db = db             return callback(err)
         })
     } catch (e) {
         throw e     }
 }

 const getDB = () => _db const disconnectDB = () => _db.close()

 module.exports = { connectDB, getDB, disconnectDB }

./index.js

 // Load MongoDB utils
 const MongoDB = require('./db/mongodb')
 // Load queries & mutations
 const Users = require('./users')

 // Improve debugging
 process.on('unhandledRejection', (reason, p) => {
     console.log('Unhandled Rejection at:', p, 'reason:', reason)
 })

 const seedUser = {
     name: 'Bob Alice',
     email: 'test@dev.null',
     bonusSetting: true
 }

 // Connect to MongoDB and put server instantiation code inside
 // because we start the connection first
 MongoDB.connectDB(async (err) => {
     if (err) throw err     // Load db & collections
     const db = MongoDB.getDB()
     const users = db.collection('users')

     try {
         // Run some sample operations
         // and pass users collection into models
         const newUser = await Users.createUser(users, seedUser)
         const listUsers = await Users.getUsers(users)
         const findUser = await Users.findUserById(users, newUser._id)

         console.log('CREATE USER')
         console.log(newUser)
         console.log('GET ALL USERS')
         console.log(listUsers)
         console.log('FIND USER')
         console.log(findUser)
     } catch (e) {
         throw e     }

     const desired = true
     if (desired) {
         // Use disconnectDB for clean driver disconnect
         MongoDB.disconnectDB()
         process.exit(0)
     }
     // Server code anywhere above here inside connectDB()
 })

./user/index.js

 const ObjectID = require('mongodb').ObjectID

 // Notice how the users collection is passed into the models
 const createUser = async (users, user) => {
     try {
         const results = await users.insertOne(user)
         return results.ops[0]
     } catch (e) {
         throw e     }
 }

 const getUsers = async (users) => {
     try {
         const results = await users.find().toArray()
         return results     } catch (e) {
         throw e     }
 }

 const findUserById = async (users, id) => {
     try {
         if (!ObjectID.isValid(id)) throw 'Invalid MongoDB ID.'
         const results = await users.findOne(ObjectID(id))
         return results     } catch (e) {
         throw e     }
 }

 // Export garbage as methods on the Users object
 module.exports = { createUser, getUsers, findUserById }


查看完整回答
反對 回復 2019-07-09
  • 3 回答
  • 0 關注
  • 869 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號