Dev.to WebDev 🛠 Dev 👁 2 📖 23 min read

Build a Music Recommender With Mongoose and MongoDB Vector Search

In the age of AI, the way that search works has changed. A traditional keyword search that only matches words in the search term is no longer sufficient for modern applications. Instead, let’s take a look at a relatively

In the age of AI, the way that search works has changed. A traditional keyword search that only matches words in the search term is no longer sufficient for modern applications. Instead, let’s take a look at a relatively new method called semantic search, which searches based on meaning rather than keywords.

In this tutorial, you’ll learn how to use MongoDB Vector Search with Mongoose by building a music recommender. You’ll type a description of a “vibe,” like “upbeat road trip with the windows down,” and get back a ranked list of songs that fit the feeling. Along the way, you’ll define a Mongoose schema and model for documents with vector embeddings, create a vector search index, and query it with $vectorSearch, using Voyage AI on MongoDB to generate the query embeddings.

This is a follow-up to another music recommender tutorial I posted, which builds the same app with the native MongoDB Node.js Driver. You don’t need to have read it to follow along. Let’s get into it!

In This Tutorial

By the end of this tutorial, you’ll know how to:

  • Define a Mongoose schema and model for documents that store vector embeddings
  • Create a vector search index from a Mongoose model
  • Embed a natural-language query with Voyage AI
  • Run $vectorSearch queries through a Mongoose model and return ranked results
  • Connect it all to a simple Express app

How It Actually Works

Before we write any code, let’s go through a quick overview of how the search functionality in this app actually works.

The key to all of this is vector embeddings. A vector embedding is a way of representing text (or other data like images or audio) as an array of numbers, or a vector. Data with similar semantic meanings produces similar vectors, so you can compare all of your vectors mathematically to find data that’s similar in meaning.

Here’s how it works in this app:

  1. Every song in our sample collection has an LLM-generated “vibe description.” This is a 2-3 sentence description of what the song “feels” like to listen to. Vector embeddings were generated from these descriptions using Voyage AI and are stored with the songs.
  2. When a user types a search query, it is converted into a vector using the same Voyage AI embedding model.
  3. We use MongoDB Vector Search, through a Mongoose model, to find the songs in the collection whose vectors are closest to the query vector.
  4. The results are returned to the user, ranked by how closely their vectors match the query vector.

Where Mongoose Fits In

Mongoose sits on top of the MongoDB Node.js driver and adds a schema layer, a model for each collection, and connection management. It doesn’t change how vector search works, and it doesn’t generate embeddings for you. Here’s what it does handle in this app:

  • Schema and model: We define what a song looks like, including the embedding field that holds its vector, and Mongoose validates every song before it’s written to the database.
  • Connection: Mongoose manages one connection that every model in the app shares.
  • Index creation: The model has a method for creating the vector search index.
  • Querying: We run the $vectorSearch aggregation stage through the model, and Mongoose sends it to MongoDB.

Full Project Code

If you want to see the full project with all of the code already written, you can find it in the Mongoose directory of the GitHub repository. Everything you need is in that directory, including the sample data and the front end. I’ll explain all the elements throughout this tutorial, and you can clone the repository and follow along as well.

Prerequisites

Before getting started, you’ll need a few things in place:

  • Node.js (v20.19 or later) installed on your machine. This is the minimum version that Mongoose 9 supports.
  • A MongoDB Atlas account with a free cluster
  • A Voyage AI API key - you can get one from the MongoDB Atlas UI

You don’t need to be a Mongoose expert, but it helps to be comfortable with the basic idea of defining a schema and creating a model from it. We’ll explain the Mongoose-specific parts as we go.

Project Setup

With that out of the way, let’s get going with the actual code.

Start by creating a new project directory and initializing it:

mkdir music-recommender-mongoose
cd music-recommender-mongoose
npm init -y

Then install the dependencies:

npm install express mongoose voyageai dotenv
npm install --save-dev typescript tsx @types/node @types/express

Mongoose bundles the MongoDB Node.js driver, so you don’t need to install the mongodb package separately.

This tutorial uses TypeScript, so create a tsconfig.json file in the root of your project:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "commonjs",
    "lib": ["ES2020"],
    "strict": true,
    "esModuleInterop": true,
    "resolveJsonModule": true,
    "outDir": "./dist",
    "rootDir": "./",
    "skipLibCheck": true
  },
  "include": ["seed/**/*", "src/**/*"],
  "exclude": ["node_modules", "dist"]
}

Then add two scripts to the scripts section of your package.json file. One starts the app, and the other seeds the database:

"scripts": {
  "dev": "tsx src/server.ts",
  "seed": "tsx seed/seed.ts"
}

Create a .env file in the root of your project with the following variables:

MONGODB_URI=<Your MongoDB Connection String>
MONGODB_DATABASE=song_vibe_search

VOYAGE_API_KEY=<Your Voyage AI API Key>

Next, you’ll need the sample data for the app.

The sample data is a small sample of 500 songs from the Free Music Archive with pre-generated “vibe descriptions” and embeddings, so we won’t need to generate any ourselves in this tutorial. You can download it by copying the data directory from the Mongoose/seed directory of the GitHub repository for this tutorial.

Create a directory called seed in the root of your project and place the data directory inside it, so that the songs are in seed/data/songs.json. Our seed script will live in this same directory, and we’ll write it later in the tutorial.

Defining the Song Model

The first Mongoose-specific piece of this app is the model. A model is how Mongoose represents a collection in your code. You describe the shape of your documents with a schema, and Mongoose gives you a model that you use to write to and read from that collection.

In the root of your project, create a new directory called src and create a new file called song.ts in that directory. This file holds our schema, our model, and the functions that connect to and disconnect from the database.

Setting up imports and constants

First, we need to set our imports, load our environment variables, and define a few constants. Paste the following code into song.ts:

import dotenv from "dotenv";
import path from "path";
import mongoose, { Schema, InferSchemaType } from "mongoose";

// Load the .env file from the project root, regardless of where the script is run from.
dotenv.config({ path: path.resolve(__dirname, "../.env") });

const MONGODB_URI = process.env.MONGODB_URI;

if (!MONGODB_URI) {
  throw new Error(
    "Missing MONGODB_URI in environment. Ensure that you have created a .env file and added your connection string."
  );
}

export const DB_NAME = process.env.MONGODB_DATABASE ?? "song_vibe_search";
export const COLLECTION_NAME = "songs";
export const VECTOR_INDEX = "vibe_vector_index";

This code loads the .env file from the root of the project, no matter where the script is run from, and makes sure the connection string is present. It also defines three constants that we’ll use throughout the app: the database name, the collection name, and the name of the vector search index that we’ll create in the next section.

Defining the schema

Now it’s time to define what a song looks like. Paste the following code into song.ts:

const songSchema = new Schema(
  {
    title: { type: String, required: true },
    artist: { type: String, required: true },
    album: { type: String, default: "" },
    fma_track_id: { type: Number, required: true },
    fma_url: { type: String, required: true },
    play_count: { type: Number, required: true },
    genre_top: { type: String, default: "" },
    genres: { type: [String], default: [] },
    vibe_description: { type: String, required: true },
    embedding: { type: [Number], required: true }, // 1024 dimensions (voyage-4-lite)
    seeded_at: { type: Date, default: Date.now },
  },
  {
    collection: COLLECTION_NAME,
    versionKey: false,
  }
);

The most important field for vector search is embedding. It’s an array of numbers, and for the voyage-4-lite model that we’re using, it contains 1024 of them. This is the field that our vector search index will point to. A plain array of numbers is what Voyage AI returns, so that’s what we’ll store. MongoDB also supports a more compact binary format for vectors, which you can read about in the Mongoose guide to vector search.

The rest of the schema describes the song’s metadata. Fields marked required must be present or Mongoose will reject the document when we try to save it, and fields with a default are filled in automatically when they’re missing. This is one of the benefits of using Mongoose: if a song is missing its embedding, we’ll find out when we insert it, instead of when search quietly leaves it out of the results.

The second argument to Schema is an options object. We use two options here:

  • collection: COLLECTION_NAME — By default, Mongoose derives a collection name from the model name. Setting it explicitly makes sure our songs always go into the songs collection.
  • versionKey: false — Mongoose normally adds a __v field to every document to track changes to arrays. We don’t modify songs after they’re inserted, so we turn it off to keep our documents clean.

Mongoose’s default behavior is also to ignore any fields that aren’t in the schema when saving. That means that if you adapt this tutorial to your own data, you’ll need to add every field you want to keep to the schema.

Creating the model

Paste the following code into song.ts to create the type and the model:

export type Song = InferSchemaType<typeof songSchema>;

// Reuse the model if it is already registered (avoids OverwriteModelError on reload).
export const SongModel =
  mongoose.models.Song ?? mongoose.model("Song", songSchema);

The first line uses InferSchemaType to generate a TypeScript type from the schema, so we don’t have to write a separate interface for a song and keep the two in sync. The second creates the model, which is what we’ll use to insert songs, create our index, and run our search. If a model named Song has already been registered, which can happen when a script reloads, we reuse it. Otherwise, Mongoose throws an OverwriteModelError.

Connecting to MongoDB

The last thing we need in this file is a way to connect to the database. Paste the following code into song.ts:

export async function connectDB(appName = "devrel-tutorial-javascript-music-recommender"): Promise<void> {
  await mongoose.connect(MONGODB_URI!, {
    dbName: DB_NAME,
    appName,
  });
}

export async function disconnectDB(): Promise<void> {
  await mongoose.disconnect();
}

Where you would create a MongoClient with the native driver, Mongoose gives you a single connection that all of your models share. You call mongoose.connect() once when your app starts, and every model uses that connection automatically. We pass the database name separately with the dbName option because our connection string doesn’t include one, and we pass an appName that identifies our app in MongoDB’s logs. When the app shuts down, mongoose.disconnect() closes the connection cleanly.

With our model defined, we’re ready to put some data in it.

Seeding the Database

Now we’ll write the script that loads the sample data into MongoDB and creates the vector search index. Create a new file called seed.ts in the seed directory. We’ll build it up in a few pieces.

Setting up the seed script

First, paste in the imports and a couple of helpers:

import fs from "fs";
import path from "path";
import mongoose from "mongoose";
import { SongModel, Song, VECTOR_INDEX, DB_NAME, COLLECTION_NAME, connectDB, disconnectDB } from "../src/song";

// Pre-built dataset (500 songs with vibe descriptions and Voyage AI embeddings).
const DATA_FILE = path.resolve(__dirname, "data/songs.json");

Notice that the script imports SongModel and our connection functions from the file we just wrote. The DATA_FILE constant points to the pre-built dataset that we copied into the seed directory earlier.

Creating the vector search index

This is the most important part of the seed script. Before MongoDB can run a vector search, it needs to know the shape of our embedding field so it can build the right index structure. Paste the following code into seed.ts:

async function createVectorSearchIndex(): Promise<void> {
  console.log("\nCreating Vector Search index...");

  try {
    await SongModel.createSearchIndex({
      name: VECTOR_INDEX,
      type: "vectorSearch",
      definition: {
        fields: [
          {
            type: "vector",
            path: "embedding",
            numDimensions: 1024,
            similarity: "cosine",
          },
        ],
      },
    });
    console.log(`  Index "${VECTOR_INDEX}" created. It may take a moment to become active.`);
  } catch (err: any) {
    if (err?.message?.includes("already exists")) {
      console.log(`  Index "${VECTOR_INDEX}" already exists — skipping.`);
    } else {
      throw err;
    }
  }
}

The model’s createSearchIndex() method creates an Atlas Search or Vector Search index on the model’s collection. We set type: "vectorSearch" to get a vector search index, and the definition describes the vector field with the following parameters:

  • type: "vector" — Marks this field as a vector field.
  • path: "embedding" — The field in our documents that holds the vectors. This matches the embedding field in our schema.
  • numDimensions: 1024 — This must match the output size of your embedding model. Voyage AI’s voyage-4-lite model produces 1024-dimensional vectors by default. If you’re using a different model, you should be able to find the number of dimensions in the documentation for your model.
  • similarity: "cosine" — This is the distance metric used to compare vectors. Cosine similarity works well for text embeddings because it measures the angle between vectors rather than their raw distance, which makes it robust to differences in text length.

The try/catch makes the script safe to run more than once. If the index already exists, we skip it instead of failing.

An alternative approach is to define the index on the schema itself by using songSchema.searchIndex(), and then call SongModel.createSearchIndexes() to create it. That keeps the index definition next to the fields it indexes. You can read more about this approach in the Mongoose guide to vector search.

Inserting the songs

Finally, paste the following code to complete the script:

async function main(): Promise<void> {
  console.log("=== Song Vibe Search - Seeding Pipeline (Mongoose) ===\n");
  console.log(`Target database  : ${DB_NAME}`);
  console.log(`Target collection: ${COLLECTION_NAME}`);

  try {
    console.log("\nConnecting to MongoDB...");
    await connectDB("devrel-github-javascript-music-recommender-seed");
    console.log("Connected.");

    // Make sure the collection exists before creating the search index on it.
    await SongModel.createCollection();

    const existingCount = await SongModel.countDocuments();

    if (existingCount > 0) {
      console.log(`\nCollection already contains ${existingCount} documents — skipping insert.`);
    } else {
      console.log(`\nLoading pre-built dataset from ${DATA_FILE}...`);
      const raw = JSON.parse(fs.readFileSync(DATA_FILE, "utf-8")) as (Omit<Song, "seeded_at"> & {
        _id?: { $oid: string };
      })[];

      // songs.json is an Extended JSON export, so _id is { "$oid": "..." }. Convert it to a real ObjectId.
      const documents = raw.map(({ _id, ...doc }) => ({
        ...doc,
        ...(_id?.$oid ? { _id: new mongoose.Types.ObjectId(_id.$oid) } : {}),
        seeded_at: new Date(),
      }));

      console.log(`Inserting ${documents.length} documents into MongoDB...`);
      await SongModel.insertMany(documents);
      console.log("  Done.");
    }

    // Always runs — safe to call when the index already exists.
    await createVectorSearchIndex();

    const finalCount = await SongModel.countDocuments();
    console.log(`\n=== Seeding complete ===`);
    console.log(`Documents in '${COLLECTION_NAME}': ${finalCount}`);
  } catch (err) {
    console.error("\nSeeding failed:", err);
    process.exit(1);
  } finally {
    await disconnectDB();
    console.log("\nMongoDB connection closed.");
  }
}

main();

This function does a few things. After connecting, it calls SongModel.createCollection() to make sure the songs collection exists before we create a search index on it. Then it checks whether the collection already has documents by using countDocuments(), so running the script a second time doesn’t insert duplicates.

If the collection is empty, the script loads the pre-built dataset from songs.json. This file is an Extended JSON export, which means each _id is stored as { "$oid": "..." }, so we convert it into a real ObjectId by using mongoose.Types.ObjectId before inserting. Then SongModel.insertMany() inserts all of the songs. This is where our schema comes into play: Mongoose validates every document against it, applies defaults, and rejects any document that is missing a required field, such as embedding.

Whether it inserts the songs or skips them because they’re already there, the script ends by creating the vector search index. The finally block closes the connection when the script completes.

Running the seed script

With everything in place, run the following command to connect to your cluster, insert the seed data, and create the vector search index:

npm run seed

This creates a new database called song_vibe_search and a new collection called songs. The songs collection contains 500 documents, each representing a song with a “vibe description” and an embedding vector. It also creates a vector search index on the embedding field.

After the script finishes, the index can take a minute or so to build. You can check its status on the Search & Vector Search page for your cluster in the Atlas UI, and you should wait until it shows as active before searching. You can also check from code by calling SongModel.listSearchIndexes() and looking for queryable: true on the index.

Now that we have our data and our vector search index, we are ready to build the main application.

Implementing Vector Search

In the src directory, create a new file called search.ts. This is where we will implement the search logic that powers our recommendations.

First, we need to set our imports, our interfaces and constants, and load our Voyage AI key. Paste the following code into search.ts:

import dotenv from "dotenv";
import path from "path";
import { SongModel, VECTOR_INDEX, connectDB, disconnectDB } from "./song";
import { VoyageAIClient } from "voyageai";

// Load the .env file from the project root, regardless of where the script is run from.
dotenv.config({ path: path.resolve(__dirname, "../.env") });

const VOYAGE_API_KEY = process.env.VOYAGE_API_KEY;

if (!VOYAGE_API_KEY) {
  throw new Error(
    "Missing VOYAGE_API_KEY in environment. Ensure that you have created a .env file and added your Voyage AI key."
  );
}

export { VECTOR_INDEX, connectDB, disconnectDB };

const voyage = new VoyageAIClient({ apiKey: VOYAGE_API_KEY, environment: "https://ai.mongodb.com/v1" });

const EMBEDDING_MODEL = "voyage-4-lite";
export const NUM_RESULTS = 5;
export const NUM_CANDIDATES = 100;

export interface SearchResult {
  title: string;
  artist: string;
  genre_top: string;
  genres: string[];
  score: number;
}

export interface SearchResponse {
  results: SearchResult[];
  queryVector: number[];
}

Notice that we pass an environment option to the Voyage AI client. It points the client at MongoDB’s Voyage AI endpoint, which is where API keys created in the MongoDB Atlas UI work. That’s why the prerequisites had you create your key through Atlas rather than directly on the Voyage AI platform. We’re also using the voyage-4-lite model, which is the same model that generated the embeddings in our sample data.

The model and connection functions come from the song.ts file that we wrote earlier. We re-export the connection functions so the server, which we’ll build shortly, can import everything it needs from this one file.

The SearchResult interface is worth a closer look. It describes the shape of what our search returns, which is a subset of the full song document: only the fields that we show to the user, plus a similarity score. We define it separately from the Song type because of how Mongoose handles aggregation, which we’ll see in a moment.

If you’re unfamiliar with vector search, some of the constants above may not make sense quite yet, but we’ll explain them more as they’re used.

Embedding the query

When a user submits a search, the first thing we need to do is embed that query by using the same Voyage AI model that was used to embed our song descriptions. Paste the following code into search.ts to create a search function and embed the query. Note the comment that shows where we will add the vector search query code in the next step.

export async function searchSongs(query: string): Promise<SearchResponse> {
  // Embed the user's query by using Voyage AI.
  const embedResponse = await voyage.embed({
    model: EMBEDDING_MODEL,
    input: [query],
    inputType: "query",
  });

  const queryVector = embedResponse.data![0].embedding!;

  // vector search query code here
}

This code specifies a few things. First, we specify the embedding model to use (in our case, we pass in the constant that we set earlier). We then pass the actual user query as an array to the input parameter. Finally, we specify the inputType as “query”. Voyage AI distinguishes between the following two types of input:

  • "document" — used when embedding data that gets saved into your database (the song vibe descriptions, in our case)
  • "query" — used when embedding a search query at runtime

Using the right input type improves retrieval quality. It’s a small but important thing to keep in mind when implementing vector search applications.

Searching with the model

Now that we have our query embedded, it’s time to use it to search for similar songs. Replace the // vector search query code here comment inside the function with the following code:

  // Run $vectorSearch against the songs collection through the Mongoose model.
  // Model.aggregate() sends the pipeline to MongoDB unchanged (Mongoose does not
  // cast it), so ranking and scores match the native driver.
  const results = await SongModel.aggregate<SearchResult>([
    {
      $vectorSearch: {
        index: VECTOR_INDEX,
        path: "embedding",
        queryVector,
        numCandidates: NUM_CANDIDATES,
        limit: NUM_RESULTS,
      },
    },
    {
      $project: {
        _id: 0,
        title: 1,
        artist: 1,
        genre_top: 1,
        genres: 1,
        score: { $meta: "vectorSearchScore" },
      },
    },
  ]);

  return { results, queryVector };

There’s no special Mongoose method for vector search. Instead, we use the $vectorSearch stage of the aggregation pipeline and run it by calling aggregate() on our model. Mongoose passes the pipeline to MongoDB as written, without casting or validating it against the schema, and returns plain JavaScript objects instead of Mongoose documents. That’s why we pass SearchResult as the type parameter to aggregate(): it tells TypeScript what shape to expect, since the results have been reshaped by the $project stage. Because Mongoose aggregations can be awaited directly, we don’t need to convert the results into an array ourselves.

The $vectorSearch stage takes the following parameters:

  • index — The name of the vector search index we created during seeding
  • path — The field in the document that holds the embedding (in this case, named "embedding").
  • queryVector — The vector we just generated from the user’s query.
  • numCandidates — How many candidate documents to consider before ranking. A higher number means the search will be more thorough but slower.
  • limit — How many results to return.

After the search stage, a $project stage shapes our output, with { $meta: "vectorSearchScore" } pulling in the similarity score for each result — a number between 0 and 1, where higher means more similar.

And that’s all we need for our search functionality! Next, we’ll build out a simple server with an endpoint to call this function.

Building the Server

Create a new file called server.ts in the src directory. This is where we will create any endpoints we might need. In this tutorial, we will create a single endpoint to search for songs.

To start, paste the following code into server.ts, which specifies the imports and sets up an Express server:

import "dotenv/config";
import express from "express";
import path from "path";
import { connectDB, disconnectDB, searchSongs } from "./search";

const app = express();
const PORT = process.env.PORT ?? 3000;

app.use(express.json());
app.use(express.static(path.join(__dirname, "../public")));

Notice that the server imports connectDB and disconnectDB instead of a database client, and that it never touches the model directly. All of the database logic stays in song.ts and search.ts.

Now, we’ll create our POST route that calls the searchSongs function we created earlier. Paste the following code into server.ts:

app.post("/api/search", async (req, res) => {
  const { query } = req.body;

  if (!query || typeof query !== "string" || query.trim() === "") {
    res.status(400).json({ error: "A search query is required." });
    return;
  }

  let results, queryVector;
  try {
    ({ results, queryVector } = await searchSongs(query.trim()));
  } catch (err) {
    console.error("Search failed:", err);
    res.status(500).json({ error: "Search failed. Please try again." });
    return;
  }

  console.log(`\nSearch: "${query.trim()}"`);
  console.log(`Results (${results.length}):`);
  results.forEach((r, i) =>
    console.log(`  ${i + 1}. ${r.title} — ${r.artist} (score: ${r.score.toFixed(3)})`)
  );

  res.json({ results });
});

In the preceding code, the function first checks that the query is valid. Then it sends the query to our searchSongs() function and returns the results. If there is an error, it returns an error message. We also log each search and its results to the terminal, which is a handy way to see the similarity scores while you experiment.

The last thing we need to do is write the code that actually starts the server and handles signals to close the connection cleanly on shutdown. Paste the following code into server.ts:

async function startServer() {
  await connectDB();
  console.log("Connected to MongoDB Atlas.");

  app.listen(PORT, () => {
    console.log(`Server running at http://localhost:${PORT}`);
  });

  process.on("SIGINT", async () => {
    await disconnectDB();
    process.exit(0);
  });

  process.on("SIGTERM", async () => {
    await disconnectDB();
    process.exit(0);
  });
}

startServer();

The server waits for connectDB() to finish before it starts listening for requests, and it calls disconnectDB() to close Mongoose’s connection when the process is told to stop.

Now that we have our server set up, let’s create a simple front end to interact with it.

Building the Front End

Since the purpose of this tutorial is the search functionality itself, we’ll keep the front end simple. It doesn’t know or care that Mongoose is behind it, because it only talks to our server through an API. That’s one of the nice things about keeping your database logic behind an endpoint.

To add it to your project, copy the public directory from the Mongoose directory of the GitHub repository and paste it into the root of your project. It’s important to keep the name as public, since our server is already set up to serve files from this directory. If you want a line-by-line walkthrough of the HTML, CSS, and JavaScript, you can find it in our original music recommender tutorial, which builds the same front end.

The only thing you need to know to follow along is how the page talks to the server. When you submit a search, the page sends a POST request to /api/search with a JSON body that contains your query:

{ "query": "upbeat road trip with the windows down" }

The server responds with a results array, which the page renders as a list of cards:

{
  "results": [
    {
      "title": "Song Title",
      "artist": "Artist Name",
      "genre_top": "Rock",
      "genres": ["Rock", "Indie-Rock"],
      "score": 0.87
    }
  ]
}

Each card shows the title, artist, and genres, along with a match percentage calculated from the score and a link to search for the song on YouTube.

Running the App

At this point, you should have everything set up. Make sure you have already run the npm run seed command from earlier in the tutorial and that your vector search index is active.

Then, run the following command to start the server:

npm run dev

Open http://localhost:3000 and try a few searches, such as:

  • “melancholy rainy afternoon”
  • “high energy workout, aggressive beats”
  • “peaceful background music for focusing”

You should see the results ranked by similarity score, with a link to YouTube so you can listen to the songs (if they’re uploaded there). You’ll also see each search and its scores printed in the terminal where the server is running. In a real application, you would want to serve the audio files or link directly to a streaming service, but for the sample data we’re using here, searching YouTube is the only free option without license limitations. If you want to expand on this with different music, check out APIs for streaming services like Spotify.

If your searches come back empty, the most likely cause is that the vector search index is still building or doesn’t exist yet. Check its status in the Atlas UI, and make sure the name in your code (vibe_vector_index) matches the name of the index.

Next Steps

And that’s the basics! You’ve now built a working music recommender that uses Mongoose, MongoDB Vector Search, and Voyage AI to find songs based on their “vibe.” There are lots of ways you can expand on this as well. Here are a few that build on what you’ve learned:

  • Filter your results. $vectorSearch accepts a filter option that narrows the search to documents that match a condition, such as songs from a particular genre. To use it, add the field to your index definition as a filter field, like { type: "filter", path: "genre_top" }, and update or recreate the index. Then add filter: { genre_top: "Rock" } to the $vectorSearch stage.
  • Define your index on the schema. As we mentioned in the seeding section, Mongoose lets you define search indexes with schema.searchIndex(), which keeps your index definitions in version control right next to your schema.
  • Store vectors more compactly. MongoDB supports a binary vector format that takes up less space than an array of numbers. The Mongoose guide to vector search shows how to use it.
  • Let Atlas generate your embeddings. With MongoDB automated embedding, MongoDB Atlas can generate embeddings for you, so your application doesn’t have to call an embedding API. The same Mongoose guide covers how to set it up.
  • Expand the data and features. You could search on other metadata or even implement user profiles so that you can create personalized playlists and recommendations based on their likes, dislikes, and listening habits.

To use your own music instead of the sample data, you’ll need to generate vibe descriptions and embeddings for it. Our original music recommender tutorial walks through that process using Gemini and Voyage AI.

Conclusion

You have now built a fully functional application that uses Mongoose, MongoDB Vector Search, and Voyage AI to recommend music based on its general “vibes.” You defined a Mongoose schema and model for documents with embeddings, created a vector search index from the model, and ran $vectorSearch queries through it. While this app is pretty simple and provides only basic functionality, you can easily use it as a baseline to build much more sophisticated applications.

Hopefully, this gives you some insight into just how well MongoDB Vector Search works with Mongoose. If you want to learn more, check out the Mongoose documentation on vector search and our documentation, or leave a comment letting me know how you’d like to see this expanded on!

📰 Read the original article on Dev.to WebDev

Originally published by Dev.to WebDev. Aggregated on AIWithGhost for educational purposes — full credit and traffic to the original publisher.