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

133
Visualizações
Javascript add each part of username to keywords array for web-socket queries?

I am trying to add the keywords of a user's username for faster querying using websocket events.

In my userSchema I have keywords index set to true:

  keywords: {
      // for live search of username
      type: [String],
      index: true,
    },

For example if a user's username is 'johnsmith', I need to save an array with the following..

user.keywords = [j, jo, joh, john, johns, johnsm, johnsmi, johnsmit, johnsmith]

I will be doing this in my userSchema.pre('save').

Below is what I am going for but how would I append the username to the parts array and then set user.keywords = parts?? Am I properly indexing the user.keywords property??

Thank you!

userSchema.pre(`save`, async function (next) {
  const user = this

  if (user.isModified(`username`)) {
    let parts = []
    for (let i = 0; i < user.username.length; i++) {
      parts.push(*???*)
    }
    user.keywords = parts
  }

  next()
})
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

As I am seeing it you are trying to make sure that if even a part of the name is searched, that it is also found when fetching from the database?

You can just use regex for the search instead of writing the possible requests in an array.

User.find({ username: {$regex : `/^${requestedSearch}/`}});

This will now find you the results where the username starts with the requested string.

If your username is "Steve" and you search for "Ste", it will return you that user from the database. You can also add options for case sensitive and so on.

Here is some more information: https://docs.mongodb.com/manual/reference/operator/query/regex/

about 4 years ago · Juan Pablo Isaza 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