【问题标题】:Inserting private variables of object mongodb插入对象mongodb的私有变量
【发布时间】: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()

【问题讨论】:

标签: node.js mongodb typescript


【解决方案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())

【讨论】:

  • 发布问题后,我也做了同样的事情。
猜你喜欢
  • 2011-03-21
  • 1970-01-01
  • 2019-01-17
  • 2018-08-18
  • 2017-10-31
  • 2012-03-02
  • 2012-01-14
  • 1970-01-01
  • 2018-06-06
相关资源
最近更新 更多