Pass exisiting Object from Parse Class otherwise create a new object

余生颓废 提交于 2019-12-07 15:37:29

Hopefully somebody has a better answer than this, but it seems that the only way to avoid saving on beforeSave is to respond with an error, and that flummoxes subsequent processing.

So, if attempting to create a duplicate is not an error from an application point of view, just a condition to be disallowed, then I think you must catch that before beforeSave, by filtering the input for duplicates.

That's not so pretty when creating in bulk, but it would go something like this:

// answer a promise for an existing email object with address==email or a promise to save a new one
function fetchOrCreateEmail(emailAddress) {
    var EmailsClass = Parse.Object.extend("Email");
    var query = new Parse.Query(EmailsClass);
    query.equalTo("address", emailAddress);
    return query.first().then(function(object) {
        if (!object) {
            object = new EmailsClass();
            object("address", emailAddress);
            return object.save();
        } else {
            return Parse.Promise.as(object);
        }
    });
}

// create Email objects with a given array of addresses, creating
// objects only for unique addresses
function createEmails(emails) {
    var toSave = _.map(emails, fetchOrCreateEmail);
    return Parse.Promise.when(toSave);
}

With this fetchOrCreateEmail function, you can create in batch as shown, or create a single like this:

fetchOrCreateEmail(emailAddress);

If you use these for all creation of Email objects, you'll no longer need (or want) the beforeSave hook for that class. I'd like to find out if there's a better solution than this one, but I think that's the best that can be done at present.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!