Skip to content Skip to sidebar Skip to footer

$addtoset To An Array But It Gives Me Null

so basically I've a wish list and I've bunch of products that I want to add inside the the wish list products array using a put request (I'm using postman btw). This is the wish li

Solution 1:

The issue is that the result from Product.find() is an array of Mongoose documents if the query matches any documents in the collection instead of a single document which you want.

Thus the expression {$addToSet: {products: product._id}} resolves to {$addToSet: {products: undefined}} because product is an array and product._id is undefined. Take this simple example

var product = [{ '_id': 1 }];
console.log(product._id) // logs undefined

To remedy this problem, you can either access the only element in the array as

wishList.update(
    { '_id': request.body.wishlistId },
    { '$addToSet': { 'products': product[0]._id} }, 
    function(err, wishlist) { ... }
);

Or use the findOne() method which returns a single document when querying the product:

Product.findOne({ '_id': request.body.productId }, function(err, product) {
    if(err) {
        response.status(500).send({err: "could not add item to wishlist"});
    } else {
        wishList.update(
            { '_id': request.body.wishlistId },
            { '$addToSet': { 'products': product._id } }, 
            function(err, wishlist) { ... }
        );
    }
});

The findById() method is also useful in this case i.e.

Product.findById(request.body.productId, function(err, product) {
    if(err) {
        response.status(500).send({err: "could not add item to wishlist"});
    } else {
        wishList.update(
            { '_id': request.body.wishlistId },
            { '$addToSet': { 'products': product._id } }, 
            function(err, wishlist) { ... }
        );
    }
});

Post a Comment for "$addtoset To An Array But It Gives Me Null"