0

Parse.Cloud.beforeSaveParse-Server. 这条线让我很困惑:

request.object.set("dbCount", 0);

它以前一直在工作。但是由于我进行了服务器更新,因此按照(cedar-14堆栈即将报废)的要求位于heroku-18堆栈上。它不再起作用了。HEROKU

此行的目的是在数据库中存储新项目时将初始化为零的计数器粘贴。但是,尽管该项目是按应有的方式创建的,但缺少“dbCount”字段。这是为什么?什么是创建该字段的正确代码?

作为参考,这里是 beforeSave 函数的相关代码:

Parse.Cloud.beforeSave("TheCollection", async (request) => {
 if (!request.object.isNew()) return;
 var query;
 query = new Parse.Query("TheCollection");
 query.equalTo("TITLE",request.object.get("TITLE"));

 await query.find().then
 (function(resUnit) {
  // If there is already a Unit with the same Title, we return an error.
  if (resUnit.length) throw "TITLE-USED";

  var query;
  query = new Parse.Query("TheCollection");
  var token = request.user.getSessionToken();
  query.find({sessionToken: token}).then
  (function(resUnit) {
    ... some useful processing ...
    // This next line is not working as it used to.
    request.object.set("dbCount", 0);
   });
  });
 });
4

1 回答 1

1

您可能错过了“返回”,并且在您的承诺解决之前进行了保存。我还看到您在嵌套范围内使用相同的变量“resUnit”,这可能会混淆它的使用。

Parse.Cloud.beforeSave("TheCollection", async (request) => {
 if (!request.object.isNew()) return;
 var query;
 query = new Parse.Query("TheCollection");
 query.equalTo("TITLE",request.object.get("TITLE"));

 await query.find().then
 (function(resUnit) {
  // If there is already a Unit with the same Title, we return an error.
  if (resUnit.length) throw "TITLE-USED";

  var query;
  query = new Parse.Query("TheCollection");
  var token = request.user.getSessionToken();
  >>>> return <<<<< query.find({sessionToken: token}).then
  (function(resUnit) {
    ... some useful processing ...
    // This next line is not working as it used to.
    request.object.set("dbCount", 0);
   });
  });
 });

如果你想更进一步,我会充分利用 async 和 await 来扁平化你的代码。通过使用平面代码,您可以消除很多允许错误的混乱

Parse.Cloud.beforeSave("TheCollection", async (request) => {
 if (!request.object.isNew()) return;
 const query = new Parse.Query("TheCollection");
 query.equalTo("TITLE",request.object.get("TITLE"));

 const resUnit1 = await query.first()
 // If there is already a Unit with the same Title, we return an error.
 if (resUnit) throw "TITLE-USED";

  const query2 = new Parse.Query("TheCollection");
  const resUnit2 = await query2.find({sessionToken: request.user.getSessionToken()})
  ... some useful processing ...
  request.object.set("dbCount", 0);
 });
于 2020-03-25T07:53:48.607 回答