【发布时间】: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