簡體   English   中英

使用 mongoose 查找 mongodb 中的文檔

[英]Find documents in mongodb using mongoose

我有兩個分開的 collections 一個用於產品,一個用於類別 我的產品架構:

const productSchema = new mongoose.Schema({
  name: { type: String, required: true },
  description: { type: String, required: true },
  catalogNumber: { type: Number, required: true },
  barCode: { type: Number, required: true },
  quantity: { type: String, required: true },
  transportPackages: { type: String, required: true },
  category: {
    type: mongoose.Schema.Types.ObjectId,
    ref: "ProductCategory",
    required: true,
  },
  translation: {
    en: {
      name: { type: String, required: true },
      description: { type: String, required: true },
    },
  },
});

我的類別架構:

const productCategorySchema = new mongoose.Schema({
  name: { type: String, required: true },
  path: { type: String, require: true },
  translate: {
    en: {
      name: { type: String, required: true },
    },
  },
});

所以我想根據類別搜索來查詢產品。 我還在產品的預掛鈎中填充類別。 這是我現在的代碼,它不僅適用於嵌套字段。 在此處輸入圖像描述

您需要按產品中設置的類別查找,您必須確保在創建產品時為其分配了一個類別,然后您可以使用:

Product.find({category: req.body.category})
  .populate([{ path: 'category'}])
  .exec((error, populatedProduct) => { 
      return res.send(populatedProduct)
  })

它將與產品一起返回類別信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM