首页 > 解决方案 > 如果产品已添加到使用 express.js 和 mongodb 制作的产品目录中的愿望清单/购物车中,如何获取信息

问题描述

在我的产品目录中,如果产品已经在我的愿望清单/购物车中,我该如何分配信息?我想为已经在愿望清单/购物车中的产品禁用“添加到愿望清单”。

我将 express.js 与猫鼬一起使用。目前,我将愿望清单存储在用户对象中,并引用产品。

const userSchema = new Schema({
    email: { type: String, required: true },
    password: { type: String, required: true },
    wishlist: {
        items: [
            {
                ProductId: { type: Schema.Types.ObjectId, ref: 'Product', required: true }
            }
        ]
    }
});

我使用 pug 查询产品目录Product.find({})并渲染结果。

标签: node.jsmongodbexpressmongoose

解决方案


更新
尝试这样的事情:

控制器/Store.js

const Users = require("../models/Users")
const Products = require("../models/Products")

router.post("/addToWishlist", async(req, res) =>{
  try{

    //query for specified user
    const user = await Users.findOne({
      email: req.body.email,
      password: req.body.password
    });

    //query for all products except for what's on the list
    let stuff = await Products.find(
          {_id:{ $not: {$in:[...user.wishlist.items]}}
      });
      res.status(200).json({ // or res.send/res.render
        data: stuff
      })
    });
  }
  catch(err){

    res.status(500).json({ // or res.send/res.render
      message: err.message
    })
  }
});

推荐阅读