Hi,
It looks like object.isNew() no longer returns true in the beforeSave function when a new object is created.
Please kindly take a look.
Thanks.
Sincerely,
Anthony
Sounds right. A change was made to support this in parse-cloud-express and a comparable change should be made here as well: https://github.com/ParsePlatform/parse-cloud-express/pull/5/files
any plan when this will be fixed?
Did you find a trick to get around this issue ?
Looks like isNew() looks whether there is a objectId set for the object or not.
I wonder if we should not provide the object with an objectId when triggering a beforeSave for an objectId that never existed.
I tried numerous times injecting different weird things into the object, but either am encountering a mutation on reserved keys, or that the objectId is required on finishing the fetch from the server (the way we construct objects).
@andrewimm, any chance you can point me in the right direction here? How do we manage to handle isNew() in classic cloud code on object creation?
Also, @gfosco, I don't think cloud-express handles isNew() in any way right now...
isNew dates back to legacy Backbone behavior -- it simply returns the lack of an object id. It should not be confused with exists(), which actually determines if the object existed before the hook ran.
I'm not entirely sure what the issue is with parse-server, since I imagine the object can't have an id before its first beforeSave, but I'm happy to help port any internal v8server logic.
If it helps, I'm using this for now
/**
* @Fix isNew
* @returns {boolean}
*/
Parse.Object.prototype.isNew = function () {
var createdAt = this.createdAt,
updatedAt = this.updatedAt;
if(!createdAt || !updatedAt) {
return true; // This is unlikely to ever be called.
}
return moment(updatedAt).diff(moment(createdAt), 'millisecond') === 0;
};
@omairvaiyani Wouldn't that always return true until you update an object?
Looks like our exists() is actually properly working, so using it with the current latest SDK is definitely the way to go, compared to using any workaround for isNew(), which doesn't actually quite work.
I am going to test beforeSave hooks on the classic Parse right now, but I also feel that we don't handle isNew() there at all.
Looked into the source a bit now and found req.original which is undefined if the object didn't exist before. This means that req.object.isNew() can simply be replaced by !req.original?
That also works.
I actually just found out that we never were setting the objectId on a beforeSave hook for new objects, so my assumptions here are incorrect from the start. Working on a fix right now.
Most helpful comment
Looked into the source a bit now and found
req.originalwhich is undefined if the object didn't exist before. This means thatreq.object.isNew()can simply be replaced by!req.original?