简体   繁体   English

如何通过 mongoose 中的填充字段查找文档

[英]how to find document by the populate field in mongoose

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'我想按游戏状态为“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 output 仍然相同,但对于游戏状态为“N”的产品,它显示 null

I heard that we could use aggregation with $lookup but I still don't know how to that我听说我们可以将聚合与 $lookup 结合使用,但我仍然不知道该怎么做

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);

try this way:试试这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM