-
-
Notifications
You must be signed in to change notification settings - Fork 3.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
get populated doc in middleware #2223
Comments
Can you clarify, preferably with code example? I don't quite understand what you're trying to do. |
var mongoose = require('mongoose')
, Schema = mongoose.Schema;
var UserSchema = new Schema({
_id: {type: String},
name: {type: String}
});
var User = mongoose.model('User', UserSchema);
var AppSchema = new Schema({
_id: {type: String},
user: {type: String, Ref: 'User'}
});
AppSchema.pre('save', function(next){
var app = this;
//how can I access the full object instead of only the _id?
console.log(app.user)
next();
})
var App = mongoose.model('App', AppSchema);
var user = new User({
_id: 'test',
name: 'test user'
});
var app = new App({
_id: 'testApp',
user: user
});
app.save(); |
Unfortunately there's no really "correct" way to do this right now, mongoose does type conversion before pre save hooks, and I think that's the more right way given the way I see pre-save hooks being used. You can do something like this where you just attach an |
Thanks for the info. That's exactly the way I'm doing it now. Store the object in a temporary path like "_user" and set the value of "user" from this object. In my last middleware pre save hook i set the temporary path to undefined. It looks a bit dirty to define a path that's never saved though. |
Its a little gnarly, I admit, but I don't have a better solution right now. In practice, if I needed to do this, I'd just have a function wrapper around saving an app. |
When I create a new object and set a path to a subdoc then in the pre save middleware only the _id value of the subdoc is available.
Is there a way to get the subdoc instead of the _id or does a populate doesn't generate a roundtrip in this case?
The text was updated successfully, but these errors were encountered: