Skip to content

Instantly share code, notes, and snippets.

@smcelhinney
Last active March 25, 2023 13:12
Show Gist options
  • Save smcelhinney/90bff3a8a7e775819b5ae608ee614d40 to your computer and use it in GitHub Desktop.
Save smcelhinney/90bff3a8a7e775819b5ae608ee614d40 to your computer and use it in GitHub Desktop.

Hey, so this is the problem, I've two models Collection & Track. As you can tell, a collection can contain many tracks, but a track belongs to one collection

ModelCollection.ts

import mongoose, { Schema, model, SchemaType, SchemaTypes } from "mongoose";

// 1. Create an interface representing a document in MongoDB.
interface ICollection {
  userId: string;
  name: string;
  isPublic: boolean;
  isPasswordProtected: boolean;
  password?: string;
  isDownloadable: boolean;
  tracks: any[];
}

// 2. Create a Schema corresponding to the document interface.
const collectionSchema = new Schema<ICollection>({
  userId: { type: String, required: true },
  name: { type: String, required: true },
  isPublic: { type: Boolean, required: true, default: false },
  isPasswordProtected: { type: Boolean, required: true, default: false },
  password: { type: String, required: false },
  isDownloadable: { type: Boolean, required: true, default: false },
  tracks: [
    {
      type: SchemaTypes.ObjectId,
      ref: "Collection",
      required: false,
    },
  ],
});

// Add timestamps
collectionSchema.set("timestamps", true);

// 3. Create a Model.
export const ModelCollection =
  mongoose.models.Collection ||
  model<ICollection>("Collection", collectionSchema);

ModelTrack.ts

import mongoose, { Schema, model, SchemaTypes } from "mongoose";

// 1. Create an interface representing a document in MongoDB.
interface ITrack {
  collectionId: any;
  name: string;
  duration: number;
  bitrate: number;
}

// 2. Create a Schema corresponding to the document interface.
const trackSchema = new Schema<ITrack>({
  name: { type: String, required: true },
  duration: { type: Number, required: false },
  bitrate: { type: Number, required: false },
  collectionId: {
    type: SchemaTypes.ObjectId,
    ref: "Collection",
    required: false,
  },
});

// Add timestamps
trackSchema.set("timestamps", true);

// 3. Create a Model.
export const ModelTrack =
  mongoose.models.Track || model<ITrack>("Track", trackSchema);

When Im saving a track, I use track.save() as normal, and use the collectionId thinking it would link them. I'm using

  const collection = await ModelCollection.findById(
    "641987178ad2cc1cdf8a07ca",
    { password: 0 }
  )
    .populate("tracks")
    .exec();

to then retrieve a collection with it's tracks, but the array is always empty.

Any idea what I'm doing wrong? Thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment