Skip to content
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

Closed
henksmeba opened this issue Aug 1, 2014 · 5 comments
Closed

get populated doc in middleware #2223

henksmeba opened this issue Aug 1, 2014 · 5 comments

Comments

@henksmeba
Copy link

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?

@vkarpov15
Copy link
Collaborator

Can you clarify, preferably with code example? I don't quite understand what you're trying to do.

@henksmeba
Copy link
Author

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();

@vkarpov15
Copy link
Collaborator

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 internal field to the document and store another reference to user in that field, and then access that field from the pre-save hook.

@henksmeba
Copy link
Author

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.

@vkarpov15
Copy link
Collaborator

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants