Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

137
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda