El problema es que el resultado de Product.find()
es una matriz de documentos Mongoose si la consulta coincide con cualquier documento de la colección en lugar de un solo documento que desea.
Así, la expresión {$addToSet: {products: product._id}}
se resuelve en {$addToSet: {products: undefined}}
porque product
es una matriz y product._id
es indefinido. Tome este ejemplo simple
var product = [{ '_id': 1 }];
console.log(product._id) // logs undefined
Para solucionar este problema, puede acceder al único elemento de la matriz como
wishList.update(
{ '_id': request.body.wishlistId },
{ '$addToSet': { 'products': product[0]._id} },
function(err, wishlist) { ... }
);
O use findOne()
método que devuelve un único documento al consultar el producto:
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) { ... }
);
}
});
El findById()
El método también es útil en este caso, es decir,
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) { ... }
);
}
});