2013-06-29 24 views
0

我在nodejs中爲我的數據庫訪問定義了以下屬性。問題是我還需要爲某個函數定義的url參數。因此,我寫的輔助函數getDataUrl()如何在運行時在nodejs中定義屬性

var config = { 
    db: { 
     db: 'dbname', // the name of the database 
     host: "12.12.12.12", // the ip adress of the database 
     port: 10091, // the port of the mongo db 
     username: "name", //the username if not needed use undefined 
     password: "pw", // the password for the db access 
     url: undefined // also tried url: getDataUrl() 
    } 

}; 

function getDataUrl() { 
     var dataUrl = "mongodb://"; 
     if (config.db.username !== undefined) { 
      dataUrl += config.db.username + ':' + config.db.password + '@'; 
     } 
     dataUrl += config.db.host + ":" + config.db.port; 
     dataUrl += '/' + config.db.db 
     return dataUrl; 
} 

module.exports = config; 

但是我不希望讓此功能,但改用物業config.db.url

我現在正在努力如何做到這一點。我曾嘗試以下:

  1. url: getDataUrl()此產品:類型錯誤:無法讀取未定義
  2. 呼叫getDataUrl()然後寫入性能的特性「DB」,但是這不會覆蓋url屬性。當我然後讀取值以下錯誤發生:Cannot read property 'url' of undefined
  3. config.db.url = getDataUrl();這也不會覆蓋url屬性。

我對JavaScript和nodejs非常陌生,因此我不知道如何實現這種行爲或者甚至是可能的。

+0

#2和#3中的「這不會覆蓋url屬性」是什麼意思,你怎麼看到這個結果?它應該工作。 – Bergi

+0

但是當我讀取這些值時,我認爲這與異步調用有關嗎?我做了更新。 – tune2fs

+0

正如@MartinLinux所觀察到的,你在函數中使用'configs'而不是'config'。修復錯字和#2和#3的工作。並使用嚴格模式,以便對未聲明的變量拋出有意義的異常! – Bergi

回答

1

你可以嘗試getter property

var config = { 
    db: { 
     db: 'dbname', // the name of the database 
     host: "12.12.12.12", // the ip adress of the database 
     port: 10091, // the port of the mongo db 
     username: "name", //the username if not needed use undefined 
     password: "pw", // the password for the db access 
     get url() { 
      var dataUrl = "mongodb://"; 
      if (this.username) 
       dataUrl += this.username + ':' + this.password + '@'; 
      dataUrl += this.host + ":" + this.port + '/' + this.db; 
      return dataUrl; 
     } 
    } 
}; 
console.log(config.db.url); // automatically computed on [every!] access 
+0

這正是我需要的,謝謝。 – tune2fs

0

要解決

write url: getDataUrl() this produce: TypeError: Cannot read property 'db' of undefined

你應該改變 「CONFIGS」 變量 「配置」,在您的getDataUrl()函數:

function getDataUrl() { 
     var dataUrl = "mongodb://"; 
     if (config.db.username !== undefined) { 
      dataUrl += config.db.username + ':' + config.db.password + '@'; 
     } 
     dataUrl += config.db.host + ":" + config.db.port; 
     dataUrl += '/' + config.db.db 
     return dataUrl; 
} 
+0

對不起,這是一個錯字,我已經更新了這個問題。 – tune2fs

相關問題