0

我在 nodejs 中为我的数据库访问定义了以下属性。问题是我还需要为某个函数定义的 url 参数。因此,我编写了辅助函数getDataUrl()

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()这个产生:TypeError:无法读取未定义的属性'db'
  2. 调用getDataUrl()然后写入属性,但是这不会覆盖 url 属性。然后,当我读取该值时,会发生以下错误:Cannot read property 'url' of undefined
  3. config.db.url = getDataUrl();这个也不会覆盖 url 属性。

我对 JavaScript 和 nodejs 非常陌生,因此我不知道如何实现这种行为,甚至不知道它是否可能。

4

2 回答 2

1

You could try a 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
于 2013-06-29T13:25:22.900 回答
0

修理

写入 url:getDataUrl() 这会产生:TypeError:无法读取未定义的属性 'db'

您应该在 getDataUrl() 函数中将“configs”变量更改为“config”:

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;
}
于 2013-06-29T13:23:35.587 回答