2016-05-12 78 views
1

我使用以下環境插入對象的MongoDB私有變量

的NodeJS:5.7.1

蒙戈DB:3.2.3

的MongoDB(驅動器的NodeJS):2.1.18

TypeScript:1.8

我已經使用類型創建了一個對象CRIPT作爲

class User { 
    private _name:string; 
    private _email:string; 
    public get name():string{ 
    return this._name; 
    } 
    public set name(val:string){ 
    this._name = val; 
    } 
    public get email():string{ 
    return this._email; 
    } 
    public set email(val:string){ 
    this._email = val; 
    } 
} 

使用MongoDB的驅動程序API,我試圖插入對象

var user:User = new User(); 
user.name = "Foo"; 
user.email = "[email protected]"; 
db.collection('users').insertOne(user) 
.then(function(r){..}).catch(function(e){..}); 

當我從蒙戈控制檯查詢,以檢查插入值,使用 db.users.find({}).pretty();

它給我跟着輸出。

{ 
"_name":"Foo", 
"_email":"[email protected]", 
"name":"Foo", 
"email":"[email protected]" 
} 

爲什麼私有變量正在被存儲?我如何防止它存儲私有變量。

編輯:1 因爲,我無法停止開發應用程序,我暫時使用了一種解決方法。該域對象現在有一個額外的方法toJSON,它提供了我希望存儲在MongoDB中的結構。 例如

public toJSON():any{ 
return { 
"name":this.name 
...//Rest of the properties. 
}; 
} 

我打電話給toJSON()關於組成對象。

+2

由於性能原因編譯爲js時,私有變量與公共變量相同。 http://stackoverflow.com/questions/12713659/typescript-private-members – Zen

+0

那麼什麼是推薦的方法來只插入公共變量? – CuriousMind

回答

1

爲了真正控制事情,我建議在每個持久對象中都有一個方法,它返回要爲該對象保存的數據。例如:

class User { 
    private _name: string; 
    private _email: string; 

    public get name(): string{ 
     eturn this._name; 
    } 

    public set name(val: string) { 
     this._name = val; 
    } 

    ublic get email(): string{ 
     return this._email; 
    } 

    public set email(val: string){ 
     this._email = val; 
    } 

    public getData(): any { 
     return { 
      name: this.name, 
      email: this.email 
     } 
    } 
} 

你可能已經不僅僅是要堅持的User更多,你可以做的事情多一點通用:

interface PersistableData {} 

interface Persistable<T extends PersistableData> { 
    getData(): T; 
} 

interface UserPersistableData extends PersistableData { 
    name: string; 
    email: string; 
} 

class User implements Persistable<UserPersistableData> { 
    // ... 

    public getData(): UserPersistableData { 
     return { 
      name: this.name, 
      email: this.email 
     } 
    } 
} 

然後你就去做:

db.collection('users').insertOne(user.getData()) 
+0

發佈問題後,我做了同樣的事情。 – CuriousMind