[英]Search an array of objects to match objectId from mongodb
I'm trying to search an array of objects by a key that contains nested object id for populating.我正在尝试通过包含用于填充的嵌套对象 id 的键来搜索对象数组。
{
service: 'user',
isModerator: true,
isAdmin: true,
carts: [
{
_id: 5e1344dcd4c94a1554ae0191,
qty: 1,
product: 5e09e4e0fcda6f268cefef3f,
user: 5e0dda6d6853702038da60f0,
expireAt: 2020-01-06T14:31:56.708Z,
__v: 0
},
{
_id: 5e13455306a54b31fc71b371,
qty: 1,
product: 5e09e507fcda6f268cefef40,// object ID
user: 5e0dda6d6853702038da60f0,
expireAt: 2020-01-06T14:33:55.573Z,
__v: 0
},
],
I want to match if carts array, contains cart with a product that user is adding, to not add it the second time but instead increment qty of the existing one.我想匹配购物车数组是否包含用户正在添加的产品的购物车,而不是第二次添加它,而是增加现有产品的数量。
const itemId = req.body._id;
const userId = req.user._id;
const { qty } = req.body;
try {
const producto = await Product.findById(itemId);
const user = await User.findById(userId).populate({
path: 'carts',
});
const result = user.carts.find((o) => {
console.log(typeof o.product) // returns object
console.log(typeof producto._id); // returns object
return o.product === producto._id
});
console.log(result); // returns undefined
if (result !== undefined) {
const foundCart = await Cart.findById(result._id);
foundCart.qty += qty;
await foundCart.save();
return res.json({ message: 1 });
}
const newCart = new Cart({
qty,
product: producto,
user,
});
const cart = await newCart.save();
user.carts.push(cart);
await user.save();
return res.json({ message: 1 });
} catch (error) {
return console.log(error);
}
I think the problem is this line我认为问题是这条线
return o.product === producto._id
Can you change it like this and try?你能像这样改变它并尝试吗?
return o.product.toString() === producto._id.toString()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.