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

132
Views
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 answers
Answer question

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 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!