I am trying to create a model and then create another model and save the link to the original model using mongoose. I am looking at mongoose documentation on middleware and their hooks, but some of them don't seem to work.
This answer tells me why my init-hook does not start HERE , pre and post init only when loading a previously existing model from db. So I read that validate will work when creating a new model. Knowing that I switched from pre init to pre validate .
Here is the code for what I'm trying to do:
GroupSchema.pre('validate', function (next, data) { console.log("inside pre validate"); if (data.location) { location = new Location(data.location); data.location = location._id; location.save(function (err) { if (err) handleError(err); }); } next(); })
I know that I cannot use this because the document is not yet populated with data. That's why I have data , but it still does not work, oh, I got the parameters that I have to pass from this answer .
Any help would be appreciated.
************** ************** UPDATE
To add some clarity, using what was recommended in the answer and changing my pre validate function to the following:
GroupSchema.pre('validate', function (next, data) { console.log("inside pre validate", this); if (this.location) { location = new Location(this.location); this.location = location._id; location.save(function (err) { if (err) handleError(err); }); } next(); })
I get the following error
service err: CastError: Cast to ObjectId failed for value "[object Object]" at path "location"
This makes sense because in my model it expects an ObjectId , not the [object, Object] that I pass. However, I thought I could save the location , get the ObjectId that was generated, and save it in the group model before it throws an error. Therefore, initially using pre init , until we find out that this will not work, and now find out that pre validate will not work either. Is there a way to do what I'm trying?
Here is what I am trying in sequence:
- create location
- get a new
ObjectId - save the new location of the
ObjectId in the group instead of the object itself
The reason I tried to add this to pre is because I could have this code in one place, and it would automatically handle this when creating a group model.