4
votes

I know that Mongoose populates the _id field automatically with an ObjectID if none is given and that you can overwrite the _id when constructing and instance of the model.

What I want: create the _id from other fields in a transparent way. I want to omit the _id field when creating an instance of the model and then have a function called which fills it. This function should be declared on a Schema level and whoever uses the model does not know that _id was filled by the function instead of Mongoose.

Is there a hook or a parameter of the Schema constructor I missed?

Mongoose 3.0.x

Let's make this more concrete. Imagine a BlogPost and I want to create nice URLs by slugging the title. In order to map the slug to a Mongo Object I hash the slug and turn it into a ObjectID to leverage it's benefits. Now what I'm looking for is a transparent method which allows me to create an instance of BlogPost by only passing in title and have the slug and _id property automatically generated.

2

2 Answers

5
votes

use a setter on title which slugifies and idifies for you: https://gist.github.com/3658511

If you want to make sure your code is only executed once the object is created, check for this.isNew inside the setter.

2
votes

Is this what you are looking for?

You could define a function to create the _id before the model is saved, as in: http://mongoosejs.com/docs/middleware.html

If this middleware is called after Mongoose creates the _id by default (my guess is it's not), you could tell Mongoose to not create an _id, with the _id option. http://mongoosejs.com/docs/guide.html#options