Crud操作mongodb、节点、快递、 Mongoose

u59ebvdq  于 2022-11-13  发布在  Go
关注(0)|答案(1)|浏览(130)
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;

//创建产品

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" });
  }
});

//更新产品

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,仅包括产品&类别名称

brccelvz

brccelvz1#

我会尽力帮助你,因为我已经从你的帖子理解.首先,在产品模式中,你只保存了类别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在产品中进行更新收藏。希望这对你有帮助。谢谢

相关问题