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

495
Vistas
How to ref to multiple models mongoose mongodb

I have 3 models MonthlyMenu. FrozenFood, and DailyDeal.

I'm creating an order model where inside the item field I want to have the id of item which will be from one of the above models.

How can I ref to multiple models in a mongoose schema?

item: {
  type: mongoose.Schema.Types.ObjectId,
  required: true,
  ref: 'DailyDeal',
},
over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

You can use mongoose virtuals for that. First, enable virtuals for your order schema by doing this:

const order_schema = new mongoose.Schema({
...
  item: {
    type: mongoose.Schema.Types.ObjectId,
    required: true
  },
...
},
{
    toJSON: { virtuals: true }
});

Then define 3 virtual schemas like so:

order_schema.virtual('frommonthlymenu', {
    ref: 'monthly_menu', // Your MonthlyMenu model name
    localField: 'item', // Your local field, like a `FOREIGN KEY` in RDS
    foreignField: '_id', // Your foreign field which `localField` links to. Like `REFERENCES` in RDS
    // If `justOne` is true, 'members' will be a single doc as opposed to
    // an array. `justOne` is false by default.
    justOne: true
});

order_schema.virtual('fromfrozenfood', {
    ref: 'frozen_food',
    localField: 'item',
    foreignField: '_id',
    justOne: true
});

//Third one here...

Then you can populate frommonthlymenu or fromfrozenfood paths whenever you query your order collection.

Lead.find(search_filter)
      .populate('frommonthlymenu')
      .populate('fromfrozenfood')
      .then(result => {
          //Whichever path is populated, that's how you know the collection "item" came from.
      })
over 4 years ago · Santiago Trujillo Denunciar
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