2016-05-12 64 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