All files / src/controllers/users-controllers addToShoppingCart.js

81.81% Statements 9/11
100% Branches 2/2
100% Functions 1/1
81.81% Lines 9/11

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24      3x 3x 3x 3x         3x 3x 1x 1x     3x            
import UsersModel from '../../models/Users.js';
 
export default async function addToShoppingCart(userId, { productId, count }) {
    try {
        let addedSuccessfully = false
        const filter = { _id: userId };
        const { modifiedCount } = await UsersModel.updateOne(
            { ...filter, userShoppingCart: new RegExp(productId) },
            { $set: { "userShoppingCart.$": `${productId}-${count}` } },
            { projection: { _id: 1 } }
        );
        addedSuccessfully = !!modifiedCount;
        if (!modifiedCount) {
            const { modifiedCount } = await UsersModel.updateOne(filter, { $push: { userShoppingCart: productId + "-1" } });
            addedSuccessfully = !!modifiedCount;
        }
 
        return addedSuccessfully;
    } catch (error) {
        console.log(error);
        return null;
    }
}