我使用以下環境插入對象的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()
關於組成對象。
由於性能原因編譯爲js時,私有變量與公共變量相同。 http://stackoverflow.com/questions/12713659/typescript-private-members – Zen
那麼什麼是推薦的方法來只插入公共變量? – CuriousMind