【发布时间】:2021-07-04 06:03:21
【问题描述】:
我正在为存储在 MongoDB 中的文档构建类似 ActiveRecord 类的东西(类似于 Mongoose)。我有两个目标:
-
使用代理拦截文档上的所有属性设置器,并自动创建要发送到 Mongo 的更新查询。对于这个问题,我已经在 SO 上找到了 a solution。
-
防止从数据库中进行不必要的读取。 IE。如果在文档上执行了一个函数,并且该函数只设置属性,并且不使用文档的现有属性,那么我不需要从数据库中读取文档,我可以直接更新它。但是,如果函数使用文档的任何属性,我必须先从数据库中读取它,然后才能继续使用代码。示例:
// Don't load the document yet, wait for a property 'read'. const order = new Order({ id: '123abc' }); // Set property. order.destination = 'USA'; // No property 'read', Order class can just directly send a update query to Mongo ({ $set: { destination: 'USA' } }). await order.save();// Don't load the document yet, wait for a property 'read'. const order = new Order({ id: '123abc' }); // Read 'weight' from the order object/document and then set 'shipmentCost'. // Now that a 'get' operation is performed, Proxy needs to step in and load the document '123abc' from Mongo. // 'weight' will be read from the newly-loaded document. order.shipmentCost = order.weight * 4.5; await order.save();
我该怎么做呢?这似乎很简单:在文档对象上设置一个“获取”陷阱。如果它是第一个属性“get”,则从 Mongo 加载文档并缓存它。但是如何将异步操作放入 getter 中?
【问题讨论】:
标签: javascript node.js mongodb metaprogramming es6-proxy