【发布时间】:2016-09-08 04:44:26
【问题描述】:
我正在使用以下环境
NodeJS:5.7.1
Mongo DB:3.2.3
MongoDB(NodeJS 驱动程序):2.1.18
打字稿:1.8
我使用 Typescript 创建了一个对象
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();
它给了我以下输出。
{
"_name":"Foo",
"_email":"foo@bar.com",
"name":"Foo",
"email":"foo@bar.com"
}
为什么要存储私有变量?如何防止它存储私有变量。
编辑:1
因为,我无法停止开发应用程序,所以我暂时使用了一种解决方法。域对象现在有一个附加方法toJSON,它提供了我希望存储在 MongoDB 中的结构。
例如
public toJSON():any{
return {
"name":this.name
...//Rest of the properties.
};
}
我也在组合对象上调用toJSON()。
【问题讨论】:
-
出于性能考虑,编译成 js 时,私有变量与公共变量相同。 stackoverflow.com/questions/12713659/typescript-private-members
-
那么推荐的只插入公共变量的方法是什么?
标签: node.js mongodb typescript