【问题标题】:Crud operations mongodb , nodejs , express , mongooseCrud 操作 mongodb , nodejs , express , mongoose
【发布时间】:2022-09-23 16:05:44
【问题描述】:
import mongoose from \"mongoose\";

const productSchema = mongoose.Schema(
  {
    name: {
      type: String,
      required: true
    },
    category: {
      type: mongoose.Schema.Types.ObjectId,
      ref: \"Category\",
      required: true
    }
  },
  { timestamps: true }
);

const Product = mongoose.model(\"Product\", productSchema);

export default Product;



import mongoose from \"mongoose\";

const categorySchema = mongoose.Schema(
  {
    name: {
      type: String,
      required: true,
      unique: true
    }
  },
  { timestamps: true }
);

const Category = mongoose.model(\"Category\", categorySchema);

export default Category;

// create Products

const createProduct = asyncHandler(async (req, res) => {
  const { name } = req.body;

  const product = new Product({
    name,
    category: req.category._id
  });
  if (product) {
    const createdProduct = await product.save();
    res.status(201).json(createdProduct);
  } else {
    res.status(404).json({ message: \"Product already exists\" });
  }
});

// update product

const updateProduct = asyncHandler(async (req, res) => {
  const { name, categoryName } = req.body;
  const product = await Product.findById(req.params.id);

  if (product) {
    product.name = name;
    product.categoryName = categoryName;
    const updatedProduct = await product.save();
    res.json(updatedProduct);
  } else {
    res.status(404);
    throw new Error(\"Product not found\");
  }
});

我无法将类别数据放入其显示的产品数据中 BSON 错误,我希望数据看起来像这样。

> products = [ {
> _id : \"\", name: \"\", category : {   _id:\"\",   name:\"\"  } } ]

我想使用这些数据来创建 api - 产品名称 & 类别名称,自动为产品和类别创建 id 仅包括产品和类别名称

    标签: node.js mongodb express mongoose


    【解决方案1】:

    我会尽力帮助你,因为我从你的帖子中了解到。 首先,在产品架构中,您只保存类别 ID,而没有提及产品类别名称字段。您需要将其添加到您的 productSchema 中,如下所示。

        const productSchema = mongoose.Schema(
      {
        name: {
          type: String,
          required: true
        },
        categoryId: {
          type: mongoose.Schema.Types.ObjectId,
          ref: "Category",
          required: true
        },
        categoryName:{
          type:String
        } 
    
      },
      { timestamps: true }
    );
    
    const Product = mongoose.model("Product", productSchema);
    

    现在您要做的是,由于您拥有 categoryId,因此您必须在保存之前向您的 Category 集合发起查询,如下所示。

    // Create Products
    const createProduct = asyncHandler(async (req, res) => {
        const { name, categoryId } = req.body;
    //Querying Category collection
    const category = await Category.find({_id:categoryId})
        //Creating Product Object
         const product = new Product({
            name,
            categoryId,
            categoryName:category.name
          });
          if (product) {
            const createdProduct = await product.save();
            res.status(201).json(createdProduct);
          } else {
            res.status(404).json({ message: "Product already exists" });
          }
        });
    

    现在,您也可以将名称保存在产品集合中。 并且通过您的更新处理程序,您不应该更新产品文档中的类别名称,最佳实践是使用 req.body 中的 categoryId 并查询名称的类别集合。如果您想更改类别名称,请在您的类别集合中更改它并使用该特定对象 ID 在您的产品集合中更新它。 希望这对您有所帮助。 谢谢

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-14
      • 2021-03-17
      • 2014-10-22
      • 2011-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多