Home > Blockchain >  how to find document by the populate field in mongoose
how to find document by the populate field in mongoose

Time:12-04

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

CodePudding user response:

try this way :

   const products = await Product.find({}).populate({
        path: 'game',
        model:'Game',
        match: {'status':'Y'}
        select: 'status'
    });

CodePudding user response:

This should work for you.

const products = await Product.find({}).populate('game','status',{status:'Y'});
  • Related