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

Adding field hooks to existing model #63

Open
zuhair-naqvi opened this issue Nov 23, 2015 · 5 comments
Open

Adding field hooks to existing model #63

zuhair-naqvi opened this issue Nov 23, 2015 · 5 comments

Comments

@zuhair-naqvi
Copy link

The field hook example shows creation of a new model using mongoose.schema, how do I add field hooks to existing models?

Eg. If I want to format the a timestamp into 'x hours ago' string. Please see pseudo-code for what I'm trying to achieve:

var User = mongoose.model('User')
User._created.hooks = {
  post:  [
    (next, date) => next(moment(date).fromNow())
  ]
}
var schema = getSchema([User])

I'm sure there's a way to do this, just struggling to get my head around hooks docs!

Thanks in advance :)

@tothandras
Copy link
Contributor

@zuhair-naqvi It's not so easy. If it's an existing model you need to assign the hooks to User.schema.paths._created.options.hooks.

@zuhair-naqvi
Copy link
Author

@tothandras that worked, thanks heaps! The next thing I'm trying to figure out is how to return the formatted date which is a string as a virtual property something like User.createdAgo so I can return this in the query result but not have it persisted (I believe if I just add it to User.schema.paths the next time I save the document it will be written too?

@tothandras
Copy link
Contributor

@zuhair-naqvi Virtual fields are not supported currently (#25), but you can try to modify the paths, it might work. I can look into virtual fields today, how can we support it.

@zuhair-naqvi
Copy link
Author

I think #64 will address this use case too!

@sibelius
Copy link
Contributor

sibelius commented May 4, 2016

@zuhair-naqvi have you managed to fix this issue?

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

3 participants