Hello coding community,
I am stuck in a small mongodb problem.
I have created an array of objects
I want to search a particular number inside the below describe book array.
How can i do it:
My mongoose model is :
`
bookNumbers: [
{
book: [],
},
],
`
I have tried this below query:
`
const existingBook = await bookPaymentModel.findOne({
"bookNumbers.book": bookNumber,
});
`
I am getting the bookNumber from frontend ie.. from the input field entered by the user.
Please help me with the query of mongodb that i need to use to search inside this array.
Syntax of the altas database :
`
Its working for this particular model:
ticketNumbers: Array (3)
0: Object
ticket: Array (1)
0: 2142523
_id: 65c77fce82f4e74a53fbecbv
1: Object
ticket: Array (1)
0: 2142444
_id: 65c9b1dfef2c61aed5f97e5c
But its not working for this :
bookNumbers: Array (1)
0: Object
book: Array (3)
0: Array (4)
0: 184567
1: 184568
2: 184569
3: 184570
1: Array (4)
0: 184579
1: 184580
2: 184581
3: 184582
_id: 65cc75fa56f9f1217e37220a
`
The book array contains multiple arrays
I am saving like this for an existing user
`
const newBookOrder = await bookPaymentModel.findOneAndUpdate(
{
userId,
},
{
$addToSet: {
bookNumbers: [{ book: books }],
razorpay_payment_id: razorpay_payment_id,
razorpay_order_id: razorpay_order_id,
razorpay_signature: razorpay_signature,
},
$push: {
amount: amount,
isPaid: true,
},
}
);
`
I have tried this below query:
`const existingBook = await bookPaymentModel.findOne({ "bookNumbers.book": bookNumber, });
if (existingBook) {
return next(
errorHandler(
404,
"You have already bought this Ticket Number. Please choose another ticket number"
)
);
}
`
I want add a validation:
If a particular number is already present in the database i want to return an error
But its still getting saved in the database although it is already present in this particular collection ie.. bookNumbers
I want it should not be saved when its already present.
I am not able to find where i did the mistake.
Please help!
2
Answers
There seems to be an issue with the schema you have made. If you are only storing one field in bookNumbers that is book, then it shouldn’t be an array, it should be an object. So your schema should look like
You can search an item from an array using
$in
method. For your scenario, you can write the query asSearch an item from array
I think your problem is with the updating. You need to update the array of
books
like this:Only if
books
is an array of integers. If only an integer is provided then"bookNumbers.books": books