I am trying to create a model then create another model and save the reference to the original model using mongoose. I have been looking through mongoose's documentation on middleware and their hooks, but some of those don't seem to fire.
This answer tells me why my init hook would not fire HERE, pre
and post
init
only fire when loading a pre existing model from the db. So I read that validate
would run on the creation of a new model. In knowing that I switched from pre
init
to pre
validate
.
Here is the code for what I am 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 I can't use this
because the document is not populated with data yet. So that is why I have data
, but this still does not seem to work, oh I got which parameters I am supposed to pass in from this answer.
Any help would be appreciated.
**************UPDATE**************
To add some clarity, using what was recommended in an answer and changing my pre
validate
function to this:
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"
Which makes sense because in my model it expects an ObjectId
and not [object, Object]
which is what I am passing. However, I thought I could save the location
, get the ObjectId
that was generated and store that in the group model before it threw an error. Hence originally using pre
init
until finding out that wouldn't work and now find out that pre
validate
will also not work. Is there any way to do what I am trying?
Here is what I am trying in sequence:
- create location
- get new
ObjectId
- store new location
ObjectId
in the group instead of the Object itself
reason I was trying to add this to a pre
hook is so that I could have this code in one spot and it automatically would handle this when newing up a group model.