I have search everywhere, but not getting any solutions. Can anyone help?
I have a mongoose object like image-
Here I also get a array of product from frontend like-
products: [
{ product: "61adbb70207f1002fc7c5c2a", quantity: 1 }
{ product: "61adbb52207f1002fc7c5c27", quantity: 2 }
]
I have to find mongoose data when all the product match to the queries.
Here is my practice-
const order = await Order.exists({
products: {
$elemMatch: {
product: {
$all: input.products.map(item => item.product)
}
}
},
user: reqUserInfo._id
});
More description--
When I get from frontend this-
products: [
{ product: "61adbb70207f1002fc7c5c2a", quantity: 1 }
{ product: "61adbb52207f1002fc7c5c27", quantity: 2 }
]
then it should return true
And when I get this-
products: [
{ product: "61adbb70207f1002fc7c5c2a", quantity: 1 }
]
It also should return true
.
But When I get this-
products: [
{ product: "61adbb70207f1002fc7c5c2a", quantity: 1 }
{ product: "61b3786ba2123f03dc6da691", quantity: 2 } // This not in the database
]
or This
products: [
{ product: "61b37850a2123f03dc6da68e", quantity: 1 }
{ product: "61b3786ba2123f03dc6da691", quantity: 2 }
//This two are not in the database
]
Then should return false
How can I do that? Please help me.
CodePudding user response:
Try
const order = await Order.exists({
"products.product": {
$all: input.products.map(item => item.product)
},
user: reqUserInfo._id
});
It should working now!