使用Mongoose/MongoDB查找嵌套的嵌入式数组

sxissh06  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(205)

我尝试过过滤掉文档中的嵌套数组元素,但没有任何内容显示。
下面是我的模式:

//Product:
const productSchema = new mongoose.Schema(
  {
    productname: {
      type: String,
      required: [true, 'User must have a name'],
      unique: true,
      validate: {
        validator: function (str) {
          return validator.isAlphanumeric(str, 'en-US', { ignore: ' ' });
        },
        message: (props) => `${props.value} is not a valid username`,
      },
    },
    slug: String,
    price: {
      type: Number,
      required: [true, 'A product must have a price'],
    },
    description: {
      type: String,
      trim: true,
    },
    images: [String],
    variants: [Variant], //Schema
  },
  {
    id: false,
    timestamps: true,
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  }
);

//Variant:
const variantSchema = new mongoose.Schema(
  {
    // product: {
    //   type: mongoose.Schema.ObjectId,
    //   ref: 'Product',
    // },
    // size: {
    //   type: mongoose.Schema.ObjectId,
    //   ref: 'Size',
    // },
    // color: {
    //   type: mongoose.Schema.ObjectId,
    //   ref: 'Color',
    // },
    size: {
      type: String,
      enum: {
        values: [
          '35',
          '35.5',
          '36',
          '36.5',
          '37',
          '37.5',
          '38',
          '38.5',
          '39',
          '39.5',
          '40',
          '41',
          '41.5',
          '42',
          '42.5',
          '43',
          '44',
          '44.5',
          '45',
          '46',
          '46.5',
          '47',
          '47.5',
          '48',
          'S',
          'M',
          'L',
          'XL',
          'XXL',
          'XS',
          'Onesize',
        ],
        message: 'Please enter correct sizing format !',
      },
      required: [true, 'Please enter sizing !'],
    },
    color: { type: String, required: [true, 'Please enter color !'] },
    quantity: Number,
  },
  {
    id: false,
    toJSON: { virtuals: true },
    toObject: { virtuals: true },
  }
);

注意:变量是嵌入式的,因此导出为架构。

因此,我试图过滤掉灰色变体,如图所示:

我所做的是通过slug找到产品,并使用variant内部的color属性进行过滤。

const document = await Model.find({
 slug: req.params.slug,
 variants: {
  color: 'Grey'
 }
});

它没有显示任何内容,0
我也试过用"variants.color" : "Grey",但这一次它给了我所有的结果。所以它似乎过滤器不适用或根本不起作用。

jdgnovmf

jdgnovmf1#

根据populate()文档,这可以通过“match”选项来实现。
解决方案应该是:

const document = await Model.find({
  slug: req.params.slug
}).populate("variants", {
  match: { color: "Grey" } // query for subdocument
});

相关问题