如何在 MongoDB Schema 中搜索引用另一个 Schema 的字段?

问题描述 投票:0回答:1

我想搜索其名称在下面

DOC
架构中的产品。但产品存储为另一个带有
Product
_id
模式的参考。下面是代码-

DOC 架构

import mongoose from "mongoose";
import Product from "./Product";

const DocSchema = new mongoose.Schema({
  name: { type: String },
  address: [
    {
      region: { type: String },
      country: { type: String },
      plantlocation: { type: String },
    },
  ],
  products: [
    {
      type: mongoose.Schema.Types.ObjectId,
      ref: "Product",
    },
  ],
});

const Doc = mongoose.models.Doc || mongoose.model("Doc", DocSchema);
export default Doc;

产品架构


import mongoose from "mongoose";

const ProductSchema = new mongoose.Schema({
  name: { type: String, unique: true },
  address: [
    {
      region: { type: String },
      country: { type: String },
      plantlocation: { type: String },
    },
  ],
  installCapacity: [
    {
      year: { type: Date },
      quantity: { type: Number },
    },
  ],
});

const Product =
  mongoose.models.Product || mongoose.model("Product", ProductSchema);
export default Product;


我的API


import Doc from "@/models/Doc";
import connectToMongo from "@/middleware/db";
import catchAsyncErrors from "@/middleware/catchAsyncErrors";
import ErrorHandler from "@/utils/errorhandler";
import { NextApiRequest, NextApiResponse } from "next";
import ApiFeatures from "@/utils/apiFeatures";
import Product from "@/models/Product";

type DataType = {
  docs?: object;
  success?: boolean;
  message?: string;
  error?: {};
};

const handler = catchAsyncErrors(
  async (req: NextApiRequest, res: NextApiResponse<DataType>) => {
    if (req.method != "POST") {
      return res.status(405).json({ success: false, message: "Bad Request" });
    } else {
      try {
        const apiFeatures = new ApiFeatures(
          Doc.find(),
          req.body.query
        ).search(); // Search Class

        const docs = await apiFeatures.query;
        if (!docs || docs.length <= 0) {
          return res
            .status(404)
            .json({ success: false, message: "Docs not found" });
        }
        res.status(200).json({
          success: true,
          message: "Doc data fetched successfully",
          docs,
        });
      } catch (error) {
        console.log(error);
        return new ErrorHandler("Internal Server Error", 500);
      }
    }
  }
);

export default connectToMongo(handler);


我的 API 功能类


class ApiFeatures {
  query: any;
  queryStr: any;
  constructor(query: any, queryStr: any = "") {
    this.query = query;
    this.queryStr = queryStr;
  }
  /**
   * Builds a search query based on provided criteria
   * @returns this (for method chaining)
   */

  search() {
    let keyword: any =
      this.queryStr.product || this.queryStr.company || this.queryStr.region
        ? {
            $or: [],
          }
        : {};

    if (this.queryStr.product) {
      keyword.$or.push({
        "products.name": {
          $regex: this.queryStr.product,
          $options: "i",
        },
      });
    }

    if (this.queryStr.company) {
      keyword.$or.push({
        name: { $regex: this.queryStr.company, $options: "i" },
      });
    }

    if (this.queryStr.region) {
      keyword.$or.push({
        "address.region": {
          $regex: this.queryStr.region,
          $options: "i",
        },
      });
    }
    this.query = this.query.find(keyword);
    return this;
  }
}

export default ApiFeatures;

我想在

DOC
模式内搜索带有产品名称的内容 我正在使用
Model.find()
方法创建搜索 API,但无法在 DOC 模式中找到带有产品 ID 的“名称”字段。

有人可以帮我吗,我想根据 DOC 架构中的产品名称搜索产品。

谢谢你。

我尝试了

Doc.find({// My query }).populate('products')
,但它只是获取所有产品或退货
404 not found

javascript node.js mongodb next.js mongoose-schema
1个回答
0
投票

要填充,您可以像这样使用

await DOC.find().populate("products", "")

无论是这个,

await DOC.find().populate({path: "products", select: ""})
© www.soinside.com 2019 - 2024. All rights reserved.