Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

136
Views
How do I create a compound unique autoincrementing field in mongoose?

I would like to create a schema where I can set a specific name for a user, for example a display name that many people can have, while also allowing people to add them based on that name. My solution is to save that name into a model with two fields, one of which is the name itself, the second one having an id that represents the number of times that name is being used currently.

var DisplayName = new Schema({
   account: {
       type: ObjectId,
       ref: 'Account',
   },
   name: {
       type: String,
       trim: true,
       required: true,
   },
   number: {
       type: Number,
       required: true,
   }
});

is what I have, but I would like to be able to just say

var displayName = new DisplayName({
   name: 'name',
   account: req.user.id
});

displayName.save();

and it would automatically set the field for me?

EDIT: I realize there wasn't enough detail in the original question:

I'd like to use mongoose's built-in post-save handlers to generate this field for me on creation. It shouldn't be updated after its created, only set the first time.

about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can use a function as shown below to do that thing.

function saveDisplayName(schema) {
	var query = DisplayName.find({name: schema.name});

	query.then(function(results) {

		var userNumber = 1;
		if (results.length < 1) {
			return userNumber;
		}
		for (var i = 0;  i <= results.length - 1; i++) {
			var result = results[i];

			if (userNumber <= result.number) {
				userNumber = result.number + 1;
			}
			if (i == results.length - 1) {
				return userNumber;
			}
		}
	}).then(function(userNumber) {
		schema.number = userNumber;

		var displayName = new DisplayName(schema);

		return displayName.save();
	}).then(function(data) {
		console.log('Data saved', data)
	}).then(null, console.log);
}

about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!