猫鼬试图填充

问题描述

我有一些问题

  1. 无法填充 CartProduct,只需显示 ObjectId。
  2. 有没有办法让 CartProduct 每次创建时自动添加到?购物车。
  3. 这是架构结构的正确方式吗?

购物车

 const CartSchema = new Schema({
  active: { type: Boolean,required: true,default: true },createAt: { type: Date,default: Date.now },client: { type: Schema.Types.ObjectId,ref: "User",required: true },products: [{ type: Schema.Types.ObjectId,ref: "CartProduct" }],});

 const Cart = model("Cart",CartSchema);

购物车产品

const CartProductSchema = new Schema({
item: { type: Schema.Types.ObjectId,ref: "Product",cart: { type: Schema.Types.ObjectId,ref: "Cart",quantity: { type: Number,totalPrice: { type: Number,});

const CartProduct = model("CartProduct",CartProductSchema);

产品

 const ProductSchema = new Schema({
 name: { type: String,price: { type: Number,image: { type: String,category: { type: Schema.Types.ObjectId,ref: "Category",require: true },});

 const Product = model("Product",ProductSchema);

推车控制器

router.post("/",async (req,res) => {
 try {
  const { userId } = req.body;
   const cart = await Cart.findOne({ client: userId 
  }).populate("CartProduct");

   if (cart === null) {
     const newCart = new Cart({
       client: userId,});

    await newCart.save();

   return res.status(201).send({ cart: newCart });
  }

   res.status(200).send({ cart });
 } catch (error) {
   res.status(500).send(error);
   }
  });

将产品添加到购物车

router.post("/addProductToCart",res) => {
try {
const { item,cart,quantity,price } = req.body;

const newProduct = new CartProduct({
  item,totalPrice: price * quantity,});

await newProduct.save();

await Cart.findOneAndUpdate(
  { _id: cart },{ $push: { products: newProduct } },{
    new: true,}
);

res.status(201).send({ message: "New Product Added To Cart" });
} catch (error) {
  res.status(500).send(error);
}
});

将产品添加到购物车确实有效, 但填充不起作用

添加输出

{
"cart": {
    "active": true,"products": [
        "602bc081daf867167c2eb5da"
    ],"_id": "602aab802f625d1654805ef0","client": "601c50211c94cf5d642c67fb","createAt": "2021-02-15T17:12:32.997Z","__v": 0
 }
}

解决方法

cartSchema 中您缺少的 {

 const CartSchema = new Schema({
  active: { type: Boolean,required: true,default: true },createAt: { type: Date,default: Date.now },client: { type: Schema.Types.ObjectId,ref: "User",required: true },products: [{ type: Schema.Types.ObjectId,ref: "CartProduct" }],});

像这样导出模型

module.exports = Cart 

有没有办法让 CartProduct 每次创建,自动添加到?购物车

没有自动将 _idCartProduct 添加到 collection 的方法,因此您应该使用 findOneAndUpdate()find() 和 {{1} } 和 push in to products array

这是模式结构的正确方式

是的,是的。

所以对于填充你可以尝试:

save()

因此将 let resultCarts = await Cart.find(filter).populate("products") let resultProducts = await Product.find(filter).populate("category") 更改为 CartProduct 因为您应该将字段名称作为参数而不是架构名称传递

products

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...