简体   繁体   English

在云代码中解析查询后保留对象

[英]Retaining objects after parse query in cloud code

I am working on writing some Parse Cloud Code that pulls JSON from a third party API. 我正在编写一些Parse Cloud代码,该代码可从第三方API中提取JSON。 I would like to modify it, check and see if it already exists and if not, save it. 我想修改它,检查它是否已经存在,如果不存在,请保存它。 I am having troubles retaining the object after checking if it exists. 在检查对象是否存在后,我很难保留它。

Here is an example of what I am trying to do. 这是我正在尝试做的一个例子。 When I get to the success block, I need the original car object so that I can save it to the parse db. 当我到达成功块时,我需要原始的汽车对象,以便可以将其保存到解析数据库中。 It is undefined though. 虽然没有定义。 I am new to JS and am probably missing something obvious here. 我是JS的新手,可能在这里缺少明显的东西。

for (var j = 0, leng = cars.length; j < leng; ++j) {
    var car = cars[j];          
    var Car = Parse.Object.extend("Car");
    var query = new Parse.Query(Car);           
    query.equalTo("dodge", car.model);
    query.find({
      success: function(results) {
          if (results.length === 0) {
            //save car... but here car is undefined.
          } 
      },
      error: function(error) {
        console.error("Error: " + error.code + " " + error.message);
      }
    });
 }

If anyone could point me n the right direction, I would really appreciate it. 如果有人能指出正确的方向,我将不胜感激。 Thanks! 谢谢!

Your function returns before the find method returns. 您的函数将在find方法返回之前返回。 This is the async nature of js. 这是js的异步特性。 Use something like the async.parrallel from the async lib. 使用类似异步库中的async.parrallel之类的东西。 http://npm.im/async http://npm.im/async

Update 20150929: 更新20150929:

Here's some code to show you how I do it, this is from a side project I was working on. 这是一些代码,向您展示我是如何做到的,这是我正在做的一个辅助项目。 The data was stored in MongoDB and was accessed with the Mongoose ODM. 数据存储在MongoDB中,并通过Mongoose ODM访问。 I'm using Async waterfall as I need the value of the async function in the next method ... hence the name waterfall in the async lib. 我正在使用异步瀑布,因为在下一个方法中需要异步函数的值...因此,异步库中的名称为waterfall :) :)

 async.waterfall([
    // Get the topics less than or equal to the time now in utc using the moment time lib
    function (done) {
        Topic.find({nextNotificationDate: {$lte: moment().utc()}}, function (err, topics) {
            done(err, topics);
        });
    },
    // Find user associated with each topic
    function (topics, done) {
        // Loop over all the topics and find the user, create a moment, save it, 
        // and then send the email.
        // Creating moment (not the moment lib), save, sending email is done in the 
        // processTopic() method. (not showng)
        async.each(topics, function (topic, eachCallback) {
                processTopic(topic, eachCallback);
            }, function (err, success) {
                done(err, success);
            }
        );
    }
    // Waterfall callback, executed when EVERYTHING is done
], function (err, results) {
    if(err) {
        log.info('Failure!\n' + err)
        finish(1); // fin w/ error
    } else {
        log.info("Success! Done dispatching moments.");
        finish(0); // fin w/ success
    }
});

Promises will really simplify your life once you get used to them. 一旦习惯了,诺言将真正简化您的生活。 Here's an example of an update-or-create pattern using promises... 这是一个使用诺言的更新或创建模式的示例...

function updateOrCreateCar(model, carJSON) {
    var query = new Parse.Query("Car");
    query.equalTo("model", model);
    return query.first().then(function(car) {
        // if not found, create one...
        if (!car) {
            car = new Car();
            car.set("model", model);
        }
        // Here, update car with info from carJSON.  Depending on
        // the match between the json and your parse model, there
        // may be a shortcut using the backbone extension
        car.set("someAttribute", carJSON.someAttribute);
        return (car.isNew())? car.save() : Parse.Promise.as(car);
    });
}

// call it like this
var promises = [];
for (var j = 0, leng = carsJSON.length; j < leng; ++j) {
    var carJSON = carsJSON[j];
    var model = carJSON.model;
    promises.push(updateOrCreateCar(model, carJSON));
}
Parse.Promise.when(promises).then(function() {
    // new or updated cars are in arguments
    console.log(JSON.stringify(arguments));
}, function(error) {
    console.error("Error: " + error.code + " " + error.message);
});

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

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