插入对象mongodb的私有variables
我正在使用以下环境
NodeJS:5.7.1
Mongo DB:3.2.3
MongoDB(NodeJS驱动程序):2.1.18
TypeScript:1.8
我已经使用Typescript创build了一个对象
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 = "foo@bar.com"; db.collection('users').insertOne(user) .then(function(r){..}).catch(function(e){..});
当我从mongo控制台查询时,使用db.users.find({}).pretty();
来检查插入的值db.users.find({}).pretty();
它给了我以下的输出。
{ "_name":"Foo", "_email":"foo@bar.com", "name":"Foo", "email":"foo@bar.com" }
为什么私有variables被储存? 我怎样才能防止它存储私有variables。
编辑:1因为,我不能停止开发应用程序,我暂时使用了一个解决方法。 该域对象现在有一个附加的方法来提供结构,我希望存储在MongoDB中。 例如
public toJSON():any{ return { "name":this.name ...//Rest of the properties. }; }
我也在组合对象上调用toJSON()
。
为了真正控制事情,我build议在每个持久化对象中都有一个方法,它返回要为该对象保存的数据。 例如:
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())
- 我可以使用没有节点的Angular 2,但与Visual Studio?
- 在Node.js中使用TypeScriptasynchronous等待
- 属性'body'在types'Request'上不存在
- 在VS Code中configurationtypescript debug的launch.json
- 带有节点的内存中的Transpile TypeScript
- 包括TypeScript编译上下文中的app.component.ts
- 如何在angular度2项目中使用“regression-js”
- 如何为摩卡unit testing提供自定义错误消息的chai expect?
- grunt-typescript不会在指定的`dest`中产生js文件