我使用以下环境插入对象的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