使用解析服务器SDK设置指针

时间:2017-09-04 21:45:08

标签: javascript pointers object parse-platform parse-server

我需要创建一个新元素并从"当前商品"更新它。和旧的报价"预览提供"。这就是我所拥有的:

  this.saveCounterOffer = function(currentOffer, price) {
  price = parseInt(price, 10);

  var offers = Parse.Object.extend("Offer");
  var exchanges = Parse.Object.extend("Exchange");

  var offer = new offers(); 
  var offerQuery = new Parse.Query(offers);
  var exchangesQuery = new Parse.Query(exchanges);

  var newOffer = Object.assign(offer, currentOffer);
  delete newOffer.id;
  newOffer.set("price", price); 
  newOffer.save().then(function(response) {
      exchangesQuery.find({
        success: function(exchange) {
          exchange.forEach(function(ex) {
            if(ex.get("currentOffer").id == currentOffer.id) {
              //everything works fine until here
              ex.set("currentOffer", newOffer);
              ex.set("previousOffer", currentOffer);
              console.log('Ex:', ex);
              ex.save().then(function(response) {
                console.log('response', response);
              });
            }
          });
        }, error: function(err) {
          console.log("error", err);
        }
      });
  });

我确实在商品表中创建了一个新商品,但是我在更改Exchange表中的状态时遇到以下错误:

  {"code":111,"error":"schema mismatch for Exchange.previousOffer; 
  expected Pointer<Offer> but got Object"}

我理解它期待指针,但我不知道如何设置指针。有人可以帮忙吗?

1 个答案:

答案 0 :(得分:0)

因此,解析服务器会自动将Parse.Object转换为set()指针到另一个Parse.Object。但在您的情况下,currentOffer看起来不是Parse.Object,因此错误。

如果您拥有该对象的Pointer<Parse.Object>,则可以创建id,因为您正在使用currentOffer.id,所以看起来像这样。您只需使用Parse.Object#createWithoutData()

修改后的代码如下所示:

...
if(ex.get("currentOffer").id == currentOffer.id) {
    ex.set("currentOffer", newOffer);
    // create new pointer and set it
    var pointerToCurrentOffer = offer.createWithoutData(currentOffer.id);
    ex.set("previousOffer", pointerToCurrentOffer);
    console.log('Ex:', ex);
...

编辑:

甚至更好,像这样:

...
if(ex.get("currentOffer").id == currentOffer.id) {
    ex.set("previousOffer", ex.get("currentOffer"));
    ex.set("currentOffer", newOffer);
    console.log('Ex:', ex);
...

EDIT 2.0

此外,使用Promise时,总是一个好主意来获取错误,否则它们会完全丢失。例如,这部分代码:

...
ex.save().then(function(response) {
    console.log('response', response);
});
...

如果上述代码中发生任何错误,则会丢失。您可以执行此操作以获取错误:

...
ex.save().then(function(response) {
    console.log('response', response);
}, function (error) {
    console.error('error', error);
});
...

有关详情,请查看documentation