如何在 `beforeSave` 云函数中取消设置嵌套 属性?

How to unset nested property in `beforeSave` cloud function?

我已经扩展了 Parse.Object。现在我想在保存对象之前取消设置嵌套的 属性 。这个嵌套 属性 settings 是一个对象。

所以我的钩子看起来像这样:

Parse.Cloud.beforeSave('MyObject', req => {
   if (req.object.get('settings').propertyToUnset) {
       req.object.unset('settings.propertyToUnset');
   }
});

但是,这会产生错误 Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

unset 如何处理嵌套属性?

您可以尝试这样的操作:

Parse.Cloud.beforeSave('MyObject', async req => {
   const settings = req.object.get('settings');
   await settings.fetch();
   if (settings.get('propertyToUnset')) {
       settings.unset('propertyToUnset');
       await settings.save();
   }
});

解决方案是使用简单的 JavaScript 命令 delete 删除 属性 的嵌套对象 settings:

Parse.Cloud.beforeSave('MyObject', req => {
    if (req.object.get('settings').propertyToUnset) {
        delete req.object.get('settings').propertyToUnset;
    }
});