Crud operations mongodb , nodejs , express , mongoose

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

I'm not able to get the category data into the product data its shows BSON error , I want the data to look this way.

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

and i want to use this data to as create api - product name & category name which automatically creates a id for product & category just including products & category names

1 Answers

I will try to help you as what I have understood from your post. First of all in the product schema you are only saving category ID and you are not mentioning the product category name field. You need to add that to your productSchema as shown below.

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

Now what you have to do is that, since you have the categoryId, you have to fire a query to your Category collection before saving as shown below.

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

Now you will be able to save the name also in the product collection. And going through your update handler you should not update the category name in your product document, what the best practice is to use categoryId from req.body and query to category collection for the name. If the you want to change the category name change it in your category collection and use that particular object Id to update it in your product collection. Hope this helps you. Thanks

Related