我正在使用以下环境
NodeJS: 5.7.1
Mongo DB: 3.2.3
MongoDB (NodeJS Driver): 2.1.18
TypeScript: 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 = "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ceae3e3cceeedfea2efe3e1" rel="noreferrer noopener nofollow">[email protected]</a>";
db.collection('users').insertOne(user)
.then(function(r){..}).catch(function(e){..});
当我从 mongo 控制台查询时,要检查插入的值,使用
db.users.find({}).pretty();
它给了我以下输出。
{
"_name":"Foo",
"_email":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="89efe6e6c9ebe8fba7eae6e4" rel="noreferrer noopener nofollow">[email protected]</a>",
"name":"Foo",
"email":"<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8bede4e4cbe9eaf9a5e8e4e6" rel="noreferrer noopener nofollow">[email protected]</a>"
}
为什么要存储私有(private)变量?如何防止它存储私有(private)变量。
编辑:1
由于我无法停止开发该应用程序,因此我暂时使用了一种解决方法。域对象现在有一个额外的方法 toJSON
,它提供了我希望存储在 MongoDB 中的结构。
例如
public toJSON():any{
return {
"name":this.name
...//Rest of the properties.
};
}
我也在组合对象上调用toJSON()
。
最佳答案
为了真正控制事情,我建议在每个持久对象中都有一个方法,它返回您想要为该对象保存的数据。例如:
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())
关于node.js - 插入对象mongodb的私有(private)变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37185384/