Skip to content
Advertisement

mongodb .find elements in an array

I have an array that dynamically holds document id’s, in which I need to query another collcetion in mongo to see if the id’s match. I have this code:

let collection = database.collection('login')

    let doc = await collection.find({ email: req.session.username }).toArray()

    let array_of_docs_bought = []
    for (var i = 0; i < doc.length; i++) {
        array_of_docs_bought.push(doc[i].list_of_docs_bought)
    }


    let documents = await database.collection('documents').find({ "id": { $in: array_of_docs_bought } }).toArray()

however, doing "id": { $in: array_of_docs_bought } doesn’t iterate through the array, so it returns nothing, but when I do this:

let documents = await database.collection('documents').find({ "id": { $in: [ 'g81h8', '2ac3c', 'juc8d', 'g81h8', 'h9k2c' ] } }).toArray()

it works, because values of the array are there and their isn’t anything to iterate through. So how can I make it iterate through array_of_docs_bought, or reformat all the code all together if it makes more sense.

Advertisement

Answer

array_of_docs_bought.push(doc[i].list_of_docs_bought) seems like the likely culprit here. Depending on the shape of your data you might be pushing arrays into your array, winding up with a nested array. This would be fixed via the ‘spread operator’:

let array_of_docs_bought = []
for (var i = 0; i < doc.length; i++) {
    array_of_docs_bought.push(...doc[i].list_of_docs_bought)
}
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement