0

I'm trying to hook into the first save event when creating a new document. Looks like this.

User.schema.post('save', function (doc) {

  console.log('The user is new? ', doc.isNew);

});  

However even when I create a new user via the Keystone admin panel it returns false. Any idea why? Is the document getting touched again by Keystone in the background or something? How should I go about hooking into a new save?

Askdesigners
  • 419
  • 5
  • 15
  • In lieu of a better response from Jed, here's something that got it working. Add a new property with the .pre() method which caches the value of isNew. Then check for that in a .post() hook. I guess isNew is never true in the post hook? https://gist.github.com/aheckmann/2889412 – Askdesigners Feb 21 '15 at 16:10

1 Answers1

1

This is a mongoose thing as far as I know. After you save the object, it is no longer new. Kinda makes sense once you think about it that way. The only workaround I've found is to put a custom attribute on the object during a pretty save handler, and removing it post save after using it to determine if the object had just been saved for the first time.

Paul
  • 35,689
  • 11
  • 93
  • 122
  • right. It looks like the isNew property is only true in the .pre() hook but always false in the .post() hook. The link I posted shows a technique for doing something like you describe. Thanks for the tip! – Askdesigners Feb 21 '15 at 19:02
  • Yeah, saw your link. I was just trying to add in that it's working as designed; the designers simply had a different usage in mind for that attribute than what some of us would have liked. – Paul Feb 23 '15 at 00:52
  • 1
    It does make sense in a way. Really I suppose the object is actually *created* when you do `new Book()`and then using `.save()` is just persisting that objects. :p – Askdesigners Feb 23 '15 at 16:00