简体   繁体   English

使用Meteor将没有其方法的JS对象存储在Mongo中

[英]Store a JS object without its methods in Mongo using Meteor

I have a JS object (ES6) like this in a Meteor project: 我在Meteor项目中有一个这样的JS对象(ES6):

export class MyClass {
    constructor() {
        this.data: uuid.v4(),   
        this.updated: new Date(),
    }

    action() {
        this.updated = new Date();
    }
}

I am saving it to a MongoDB collection like this: 我将其保存到这样的MongoDB集合中:

let id = myDB.insert(new myClass());

Later, I fetch the object by Id: 稍后,我通过ID提取对象:

let persisted = myDB.findOne({ _id: id });

If I run the following, it works and updates the updated property of the object: 如果运行以下命令,它将起作用并更新对象的更新属性:

persisted.action();

Now, this is rather convenient, and I am tempted to run with it, but it appears to be storing the logic of the action method into MongoDB. 现在,这很方便,我很想使用它,但是它似乎是将action方法的逻辑存储到MongoDB中。 This seems inefficient because I will have many saved instances of MyClass all with the same action() method. 这似乎效率很低,因为我将使用相同的action()方法保存许多MyClass实例。

Is it standard practice in Meteor to store objects in this manner, or is there some way to conveniently strip the methods away from the object prior to saving it so that only the data and updated properties are stored? 流星是否以这种方式存储对象是标准做法,还是有某种方法可以在保存对象之前方便地将方法从对象中剥离出来,以便仅存储数据和更新的属性?

You could consider adding a method to your class that returns a JSON version of your object. 您可以考虑向类添加一个方法,该方法返回对象的JSON版本。 Then, you should insert this JSON version to your MongoDB. 然后,您应该将此JSON版本插入到MongoDB中。 Also, you should change your constructor to accept arguments, this will be useful when fetching the object from the database. 另外,您应该更改构造函数以接受参数,这在从数据库中获取对象时很有用。

Add this constructor to MyClass: 将此构造函数添加到MyClass中:

constructor(data, updated) {
    this.data = data;
    this.updated = updated;
}

Add the following method to MyClass : 将以下方法添加到MyClass

toJSON() {
    return {
        data: this.data,
        updated: this.updated
    }
}

Instantiate the class: 实例化该类:

let myObject = new myClass(uuid.v4(), new Date());

Then, call JSON.stringify on myObject : 然后,在myObject上调用JSON.stringify

let myObjectJSON = JSON.stringify(myObject)

Finally, insert myObjectJSON in your MongoDB collection: 最后,将myObjectJSON插入MongoDB集合中:

let id = myDB.insert(myObjectJSON);

Every time you call JSON.stringify on a object instace from a class that has a method called toJSON , this method will be called. 每次您从具有名为toJSON方法的类的对象JSON.stringify上调用JSON.stringify时,都会调用此方法。

When you fetch this document from your collection, create a new instace from MyClass passing as arguments to the constructor the fields inside the document. 当您从集合中获取此文档时,请从MyClass创建一个新实例,并将该文档中的字段作为参数传递给构造函数。

let persisted = myDB.findOne({ _id: id });
let persistedObject = new myClass(persisted.data, persisted.updated);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM