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

401
Vistas
MongoDB - Mongoose with NodeJS find and join collection

I need to find and join another collection to get the businesses data from businesses collection and the profile description which is saved in the profiles collection. Latest version of nodejs and mongoose.

businesses = await Business.find({}, "business_id name industry")
      .limit(limit * 1)
      .skip((page - 1) * limit)
      .exec();

That is the code, which I need later also for the pagination.

Now I found a solution with $Lookup in Mongoose. My code looks like

Business.aggregate([{
        $lookup: {
            from: "profiles", // collection name in db
            localField: "business_id",
            foreignField: "business_id",
            as: "profile"
        }
    }]).exec(function(err, profile) {
        console.log(profile[0]);
    });

The Business and Profile is saved with the business_id in a field. So I can't work with _id from Mongoose. I never before work with mongoose and two collections.

The issue is now that the profile[0] is not connected to the correct business. So the profile is a another one as from the business find above.

I need to find the latest 10 Businesses and join to another collection and grap also the profile details. What I make wrong here, has anyone a example for this behauivor ?

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

Use https://mongoosejs.com/docs/populate.html

As in your case you don't have ObjectId here you can use populate-virtuals

So far you've only populated based on the _id field. However, that's sometimes not the right choice. In particular, arrays that grow without bound are a MongoDB anti-pattern. Using mongoose virtuals, you can define more sophisticated relationships between documents.

const BusinessSchema = new Schema({
  name: String
});
BusinessSchema.virtual('profile', {
  ref: 'Profile', // The model to use
  localField: 'business_id', // Find people where `localField`
  foreignField: 'business_id', // is equal to `foreignField`
  // If `justOne` is true, 'members' will be a single doc as opposed to
  // an array. `justOne` is false by default.
  justOne: false,
  options: { sort: { name: -1 }, limit: 5 } // Query options, see  "bit.ly/mongoose-query-options"
});
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