In both our movie and actor schemas, we used a plugin called generateId()
.
While MongoDB automatically generates ObjectID
for each document using the _id
field, we want to generate our own IDs that are more human readable and hence friendlier. We also would like to give the user the opportunity to select their own id of choice.
However, being able to choose an id can cause conflicts. If you were to choose an id that already exists, your POST
request would be rejected. We should autogenerate an ID if the user does not pass one explicitly.
Without this plugin, if either an actor or a movie is created without an explicit ID passed along by the user, the server would complain since the ID is required.
We can create middleware for Mongoose that assigns an id
before we persist the object as follows:
// /src/models/plugins/generateId.js module.exports = function() { return function generateId(schema){ schema.pre('validate',function(next, done) { var instance = this; ...