Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

393
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda