Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

134
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda