在nodejs中搜索参考文档中的类别

yr9zkbsy  于 2023-06-05  发布在  Node.js
关注(0)|答案(2)|浏览(334)

类别架构

const CategorySchema = mongoose.Schema(
  {
    catName: { type: String, required: true }
  },
  { timestamps: true }
);

产品架构

const ProductSchema = new mongoose.Schema(
  {
    brand: { type: String, required: true },
    title: { type: String, required: true },
    categories: { type: mongoose.Schema.Types.ObjectId, ref: "Category" },
  },
  { timestamps: true }
);

这是我的代码,在知道我的产品模型中存储的数据是类别模型的引用ID的情况下搜索类别名称

const qCategory = req.query.category;

else if (qCategory) {
      products = await Product.find({
        categories: {
          catName: qCategory
        }
      }).populate("categories");
    }

我已经尽力了,请帮帮我。
我需要按类别搜索

tvz2xvvm

tvz2xvvm1#

首先需要获取类目的id,然后使用这个id查询产品:

const qCategory = req.query.category;    

const category = await Category.findOne({ catName: qCategory });

if (category) {
    products = await Product.find({ categories: category._id }).populate("categories");
}

另外,我认为你想改变的名称为单数类别,因为目前它只允许存储一个。
如果你想存储多个,你需要为此进行更改:

categories: [{ type: mongoose.Schema.Types.ObjectId, ref: "Category" }],
0aydgbwb

0aydgbwb2#

你可以试试这个:

router.get("/search/:key", async (req, res) => {
    try {

        const category = await Category.findOne({ catName: req.params.key });

        let products = await Product.find({
            $or: [
                { title: { $regex: req.params.key, $options: "i" } },
                { brand: { $regex: req.params.key, $options: "i" } },
                { categories: category?._id }
            ]
        });
    } catch {

    }
});

相关问题