skip to Main Content

My Product Schema Look like this.

import mongoose from 'mongoose';

const productSchema = new mongoose.Schema(
   {
       name: { type: String, required: true },

       game: {
           type: mongoose.Schema.Types.ObjectId,
           ref: 'Game',
           required: true,
       },
       category: {
           type: mongoose.Schema.Types.ObjectId,
           ref: 'Category',
           required: true,
       },
       slug: { type: String, required: true, unique: true },
       image: { type: String, required: true },
       price: { type: Number, required: true },
       nominal: { type: Number, required: true },
       description: { type: String, required: true },
   },
   {
       timestamps: true,
   }
);

const Product =
   mongoose.models.Product || mongoose.model('Product', productSchema);
export default Product;

My schema game

import mongoose from 'mongoose';

const gameSchema = new mongoose.Schema(
    {
        name: {
            type: String,
            require: [true, 'Type cant be empty'],
        },
        status: {
            type: String,
            enum: ['Y', 'N'],
            default: 'Y',
        },
        thumbnail: {
            type: String,
            require: [true, 'Type cant be empty'],
        },
    },
    { timestamps: true }
);
const Game = mongoose.models.Game || mongoose.model('Game', gameSchema);
export default Game;

I want to find a product by the game status is ‘Y’

I try to do like this

const getHandler = async (req: NextApiRequest, res: NextApiResponse) => {
        await db.connect();
        const options = { status: { $regex: 'Y', $options: 'i' } };
        const products = await Product.find({}).populate({
            path: 'game',
            select: 'status',
            match: options,
        });

        res.send(products);
        await db.disconnect();
    };

but is not work
is not filtering.
the output is still the same but for the products with a game status is ‘N’ it shows null

I heard that we could use aggregation with $lookup but I still don’t know how to that

2

Answers


  1. try this way :

       const products = await Product.find({}).populate({
            path: 'game',
            model:'Game',
            match: {'status':'Y'}
            select: 'status'
        });
    
    Login or Signup to reply.
  2. This should work for you.

    let data = await Product.aggregate([
    {
      $lookup: {
        from: "games", //Your model name which is in mongoose DB
        localField: "game", //field name of product which contains game id
        foreignField: "_id", // _id of game
        pipeline: [
          {
            $match: {
              status: "Y",
            },
          },
        ],
        as: "game", //name of result
      },
     },
     { $unwind: "$game" },// this will make your array to object and also it will remove all null entry.
    ]);
    console.log(data);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search