Home > Software design >  Javascript add each part of username to keywords array for web-socket queries?
Javascript add each part of username to keywords array for web-socket queries?

Time:12-08

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()
})

CodePudding user response:

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/

  • Related