'how to make an inner join with mongodb and mongoose and nestjs?

I have a system with mongodb genericized by mongoose in nest js how do I bring customer and product data in the same request

in the database the data is like this:

  "_id": "621d2137abb45e60cf33a2d4",
        "product_id": [
            "621cedbf79d68fb4689ef0cb",
            "621cedbf79d68fb4689ef0cb",
            "621cedbf79d68fb4689ef0cb"
        ],
        "client_id": "621d19f890ec693f1d553eff",
        "price": 597,
        "__v": 0

my serviçe:

  findAll() {
    return this.sealsModel.find().exec();
  }

This way didn't work:

findAll() {
    var a = this.sealsModel.find().exec()
    return this.sealsModel.aggregate([{
        $lookup: {
          from: 'seals',
          localField: 'client_id',
          foreignField: '_id',
          as: 'client' 
        }
    }])            
    .exec()
}

but return this:


 "_id": "621d3e0a1c3bcac85f79f7cc",
        "product_id": [
            "621cedbf79d68fb4689ef0cb",
            "621cedbf79d68fb4689ef0cb",
            "621cedbf79d68fb4689ef0cb"
        ],
        "client_id": "621d19f890ec693f1d553eff",
        "price": 597,
        "__v": 0,
        "client": []



Solution 1:[1]

An alternative to Mongo's $lookup operator is Mongoose's populate function. In order to use it properly, you first have to update your model.

You should have a client model that looks like this:

// /models/Client.js
const mongoose = require("mongoose");

const clientSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  ... // the rest of your fields
});

module.exports = mongoose.model('Client', clientSchema);

The key thing to notice here is the last line. The model is referenced as "Client".

The change you have to make is mainly in your Seal model :

// /models/Seal.js
const mongoose = require("mongoose");

const sealSchema = mongoose.Schema({
  _id: mongoose.Schema.Types.ObjectId,
  client_id: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "Client" // We use the same name we gave to our client model in the last file
  }
});

module.exports = mongoose.model('Seal', sealSchema);

Then, in your code, you should be able to use:

const Seal = require("YOUR_PATH/models/Seal.js")

Seal.find().populate("client_id")

One important side note: your model shows the mongo ID as a string

"_id": "621d3e0a1c3bcac85f79f7cc",
"client_id": "621d19f890ec693f1d553eff", <---

Make sure that the field client_id is of type ObjectId or it won't work:

"client_id": ObjectId("621d19f890ec693f1d553eff")

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JrmDel