首页 > 解决方案 > Mongodb 无法从 $addToSet 运算符添加所有元素,省略了一些元素

问题描述

我有一个商店和一个产品。仅当产品存在于数据库中时,我才尝试将产品添加到用户的购物车中。立即请求将产品添加到购物车,查询产品集合以检查产品是否存在,如果产品存在,我更新购物车:

  1. 产品所属商店的 id,从初始产品查询中获取。
  2. 产品的 id 也是从检查产品存在的相同初始查询中获得的。
  3. 来自请求有效负载的产品数量。
  4. 价格也像以前一样来自产品查询。

现在的问题是;仅保存产品的产品 ID 和数量,省略价格和商店 ID。

这是产品的架构

var ProductModelSchema = new Schema({
    name: {type: String, required: true},
    desc: {type: String, required: true},
    images: {type: Array, required:true},
    price: {type: Number, required: true},
    category: {type: String, required: true},
    store: {type: Schema.Types.ObjectId, required: true, ref: 'store'},
    uploadDate: {type: Date, required: true, default: Date.now},
    uploadedby: {type: String, required: true},
});

这是购物车的架构

var CartModelSchema = new Schema({
    _userId: {type: Schema.Types.ObjectId, required:true, ref: 'user'},
    items: [{
           _id:{type: Schema.Types.ObjectId, required:true, ref: 'product', unique: true},
            qty:{type: Number, required: true},
            store: {type: Schema.Types.ObjectId, required: true, ref: 'store', unique: true},
            price: {type: Number, required: true}
        }],
})
   module.exports = {
         addtocart: (req, res)=>{
             let payload = req.decoded;
             User.findOne({_id: payload.user}, (error, user)=>{
                 if(error){
                     return res
                         .status(403)
                         .json(ERR("Error encountered, user unknown"));
                 }if(user){
                      //if user is signed in, query product collection for the particular product
                     Product.findOne({name: req.body.name}, (error, product)=>{
                         if(error){
                             return res
                                 .status(403)
                                 .json(ERR("Error encountered while searching for product"));
                         }if(product){
                     // if product exist in the product collection, query cart to check if it already contains product
                            Cart.findOne({'items._id': product._id, _userId: user._id}, (error, item)=>{
                                if(error){
                                    return res
                                         .status(402)
                                         .json(ERR("Error encountered when searching for item in your Cart"));
                                }
                             // Product cannot be re-added to cart, if already present
                                if(item){
                                    return res
                                     .status(403)
                                     .json(ERR("We can't re-add an already existing item to your Cart"));
                                }else{
                         //if product never existed in the cart, update cart by adding the product id, product quantity, product price,and product store to the cart items array
                                     Cart.updateOne({_userId: user._id},
                                         {$addToSet:{items: [{_id: product._id, qty: req.body.qty, store: product.store, price: product.price}]}},
                                         {upsert: true},
                                         (error, cart)=>{
                                             if(error){
                                                 return res
                                                     .status(403)
                                                     .json(ERR("Issue encountered while trying to add item to cart"));
                                             }if(cart){
                                                 return res
                                                     .status(200)
                                                     .json(SUCCESS(product.name + " added to cart"));
                                             }else{
                                                 return res
                                                     .status(403)
                                                     .json(ERR("problem"))
                                             }
                                         })
                                     }
                            })
                         }else{
                             return res
                                 .status(401)
                                 .json(ERR("The product you asked for doesn't exist"))
                         }
                     })
                 }else{
                     return res
                         .status(404)
                         .json(ERR("User does not exist."))
                 }
           })
       }}

这是邮递员查询在此处输入图像描述

这是我测试端点后得到的输出

 db.carts.find().pretty()
{
        "_id" : ObjectId("5f3a636f0bba3e016eb7dc14"),
        "_userId" : ObjectId("5eebaf66ee5dab56e85b9576"),
        "__v" : 0,
        "items" : [
                {
                        "_id" : ObjectId("5f2c0e1c832b456fe8228f54"),        
                        "qty" : 1
                }
        ]
}

标签: node.jsmongodbexpressmongoose

解决方案


我已经能够解决这个问题,我导入了一个错误的模型,它是一个旧模型,只有 _id 和 qty 作为项目对象属性。


推荐阅读