Build a Music Recommender With Mongoose and MongoDB Vector Search

2026-12-01来源 dev.toEnglish

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 functi...

原文:https://www.a8q9.cn/en/article/build-a-music-recommender-with-mongoose-and-mongodb-vector-search-4f11ba.html

相关文章