vercel / mongodb-starter

A developer directory built on Next.js and MongoDB Atlas, deployed on Vercel with the Vercel + MongoDB integration.
https://mongodb.vercel.app
466 stars 147 forks source link

How to Enable Searching? #17

Open diathekez opened 1 year ago

diathekez commented 1 year ago

Hello. I'm new to TypeScript, and still new to programming in general. Forgive me if the answer is obvious, but how do I enable searching? Or is it already enabled and I just have to tweak some things? Thanks in advance :) Please feel free to DM me.

Falowo commented 1 year ago

I also want to know

AnonymousSB commented 3 months ago

The "issue" with the search as it's programmed is that you need to look at the searchUser query inside lib/api/user.ts to see that it's expecting you to define a search index inside MongoDB Atlas. Additionally, the aggregate function is filtering out users who are not verified, which none are in the sample set that is loaded into the test users database.

Here is how you can get search working locally:

Step 1: Go to this file and look at the commented out code that starts with name-index is a search index as follows

https://github.com/vercel/mongodb-starter/blob/772e42a1fd5dbac0d8a8165537ca2ca0264f7838/lib/api/user.ts#L130-L151

Step 2:

  1. Go to MongoDB Atlas
  2. Click on "Database" on the left
  3. Click on "Browse Collections" button in the middle,
  4. Expand "test" and click "users" on the left pane
  5. Click "Search Indexes" in the right pane.
  6. Click "Create Search Index" and use the defaults to continue.
  7. Name your index name-index as shown in the user.ts file.
  8. Click "Refine Your Index"
  9. Scroll up and click "Add Field Mapping"
  10. Click "Customized Configuration" at the top
  11. For each field; followers, name, username; add one by one with the correct data type shown in user.ts. The analyzer and searchAnalyzer default to the correct values
  12. Wait for the search index to be built, it takes a few minutes

Step 3: Getting results The following lines of code filter results using the "verified" field on each user... Astute programmers will notice this field does not exist on the test.users collection... So you have a few options.

  1. Remove this filter
  2. Add the verified boolean field to each user in the test.users collection that you want to appear in search
  3. Search the collection your own user is added to after login. I noticed that when you authenticate as yourself using Github, the [...nextauth].ts file adds this flag to your MyFirstDatabase.users collection; however, that is not the collection search is looking over.

https://github.com/vercel/mongodb-starter/blob/772e42a1fd5dbac0d8a8165537ca2ca0264f7838/lib/api/user.ts#L178-L183