Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

223
Vistas
Mongoose Populate, Do I have to keep schemas in the same file?

I am trying to populate by using Mongoose. This is what it looks like so far:

schema.ts

const UserSchema = new mongoose.Schema({
  id: String,
  name: String,
});
const UserModel = mongoose.model("User", UserSchema, "users");

const ShiftSchema = new mongoose.Schema({
  userId: {
    type: String,
    required: true,
  },
  date: {
    type: String,
    required: true,
  },
  startTime: String,
  endTime: String,
});

ShiftSchema.virtual("user", {
  ref: "User",
  localField: "userId",
  foreignField: "id",
  justOne: true,
});

const ShiftModel = mongoose.model("Shift", ShiftSchema, "shifts");

export default ShiftModel;

shift.ts

const shifts = await ShiftModel.find({}).populate("user");

So this code is working fine, it is working as expects and populating user data into shift data.

What I'm currently having trouble with is organizing this. I need to separate schemas into separate files however if I try to separate the userSchema and UserModel into a different file, populate doesn't work anymore. Any ideas on a workaround for this?

Also, by the way, I am using a custom ID and not the default ID supplied by MongoDB.

What I've tried:

import mongoose from "mongoose";

export const UserSchema = new mongoose.Schema({
  id: String,
  name: String,
});
export const UserModel = mongoose.model("User", UserSchema, "users");

When I try to run my script, I get an error saying that Schema hasn't been registered for model "User".

about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda