我在 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
。
我目前正在努力如何做到这一点。我尝试了以下方法:
- 写
url: getDataUrl()
这个产生:TypeError:无法读取未定义的属性'db' - 调用
getDataUrl()
然后写入属性,但是这不会覆盖 url 属性。然后,当我读取该值时,会发生以下错误:Cannot read property 'url' of undefined
- 写
config.db.url = getDataUrl();
这个也不会覆盖 url 属性。
我对 JavaScript 和 nodejs 非常陌生,因此我不知道如何实现这种行为,甚至不知道它是否可能。