These are chat archives for Automattic/mongoose

20th
May 2016
daljitsoftware
@daljitsoftware
May 20 2016 09:26
I am using flux + react, where my flux store consist of many mongoose models Please see:
http://stackoverflow.com/questions/37326585/flux-store-and-mongoose-model-code-sharing
Is this is the right approach
Umair Sarfraz
@aquadestructor
May 20 2016 18:24
I am having some issues understanding mongoose pre and post hooks, can anybody help me out?
James Lee
@uptownhr
May 20 2016 19:59
whats the question?
Umair Sarfraz
@aquadestructor
May 20 2016 20:17
var ClubSchema = new Schema({
  created: {
    type: Date,
    default: Date.now
  },
director:{
    type: Schema.ObjectId,
    ref: 'User'
  }
I want to throw and error if director already has some value. How can I do this?
@uptownhr
James Lee
@uptownhr
May 20 2016 20:41
you can use the pre hook then
check if this.director is set
Umair Sarfraz
@aquadestructor
May 20 2016 20:45
@uptownhr 1- I am trying to trigger this via update function not via save. 2- If I use it with pre hook, this would be triggered on every save call to ClubSchema, which is expensive right?
Any other way to achieve this? As a workaround, I am handling it via a callback function in the server controller
James Lee
@uptownhr
May 20 2016 20:49
the update does not trigger the pre save hook
you'd need to use the pre update hook
Umair Sarfraz
@aquadestructor
May 20 2016 20:51
Can you provide me an example, please?
scroll doesn to the bottom
basically you'd be using a query middleware
but you will not be able to use this ...
to refernce the document
Umair Sarfraz
@aquadestructor
May 20 2016 20:53
Yeah I have gone through the docs and I understand what you are referring to. Is this the best possible way to overcome a situation like this?
Ah all right.
James Lee
@uptownhr
May 20 2016 20:53
you'll need to use 'this' to pull the documents in and check for the existence of director
yea
no other way i believe
Umair Sarfraz
@aquadestructor
May 20 2016 20:54
I see. Basically I can’t use this properly with update. I think the issue is because of this. Its stated in the docs
Query middleware differs from document middleware in a subtle but important way: in document middleware, this refers to the document being updated. In query middleware, mongoose doesn't necessarily have a reference to the document being updated, so this refers to the query object rather than the document being updated.
James Lee
@uptownhr
May 20 2016 20:55
yea
it goes back to what update is meant to do
update accepts a query
its like a find
so you're hooking into a query
what is the reason you are not using save?
Umair Sarfraz
@aquadestructor
May 20 2016 20:56
Can I PM you?
James Lee
@uptownhr
May 20 2016 20:56
sure