All files / src/controllers/products-controllers addRatingToProduct.js

58.33% Statements 7/12
50% Branches 1/2
100% Functions 1/1
54.54% Lines 6/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        2x 2x 2x 2x 2x 2x                      
import ProductsModel from "../../models/Products.js";
import toObjectId from "../../utilities/toObjectId.js";
 
export default async function addRatingToProduct(productId, userId, theRating) {
    try {
        const raterId = toObjectId(userId);
        const rating = { raterId, rating: theRating };
        const filter = { _id: productId, $nor: [{ "ratings.raterId": raterId }] }
        const response = await ProductsModel.updateOne(filter, { $push: { ratings: rating } });
        if (response.modifiedCount) return true
        else E{
            const filter = { _id: productId, "ratings.raterId": raterId }
            const response = await ProductsModel.updateOne(filter, { $set: { "ratings.$.rating": theRating } });
            return !!response.modifiedCount
        }
    } catch (error) {
        console.log(error)
        return null;
    }
}