Search code examples
node.jsmongodbrestmongoosemean-stack

Auto-generate employee ID using mongoose and nodejs


I'm working on a web app project using MEAN stack technology. I want to generate 'empId' (employee ID) automatically when a request to add a new employee is received. How can I do the same and store the generated 'empId' in the same document where I keep employee details?

Thanks in advance!


Solution

  • Unless there are other requirements that haven't been stated, you can simply generate empId when handling the request to add a new employee, and include it with other properties that may be supplied by the caller:

    const schema = new Schema({ name: String, empId: String });
    const Employee = model('Employee', schema);
    
    // then when handling an "add employee" request:
    
    const { name } = req.body; // properties from request
    const empId = generateEmployeeId(); // e.g., "uuid()"
    const employee = new Model({name, empId})
    

    You can also automatically include an empId with each new Document by supplying it as a default in the mongoose Schema. Combine that with a library like nanoid (that gives you a bit more control over the ids generated) and you would have something like:

    const schema = new Schema({
      name: String,
      empId: {
        type: String,
        default: () => nanoid()
      }
    })
    

    Also keep in mind that mongodb will always create a unique identifier for each document in the _id property.