0

I have a database collection where each row has a unique ID associated with it. I want to be able to query my database and match data from it with the IDs in each of the objects from an array. The _ids are a string.

Collection Example:

"_id" : "453241", 
"name" : "Item1", 

"_id" : "621984", 
"title" : "Item2", 

"_id" : "832127", 
"title" : "Item3", 

The object would look something like this:

query = [{"_id":"621984","quantity":"3"},{"_id":"832127","quantity":"2"}]

The desired output would be something like this (I do not want to write to the database the quantity):

output = [{"_id":"621984","Item2", "quantity":"3"},{"_id":"832127", "Item3" ,"quantity":"2"}]

From the other threads, I read from what I understand we have to use the $is to match the data. Like the one in this example MongoDB select where in array of _id? However, the issue with this is that they are using an array of IDs. And I'm not sure how we would append the quantity to this value.

I also considered iterating through a loop of all of the objects inside of the array and then searching the database. And appending the output to an array. This would be most beneficial as I would want the overall output to include the quantity as well. console.logging result in this case works and outputs the designated ID table however when attempting to append the values to output and then returning this does not work and returns an empty array.

output = []
for (item in query) {
    collection.find({"id": item._id}).then((result) => { output.push(result + item.quantity) })
}
return output

Any ideas or help would be greatly appreciated thanks.

Hamada
  • 1,836
  • 3
  • 13
  • 27

1 Answers1

1

I've run into very similar situations with my own implementations as far as efficiency is concerned. The approach that I ended up taking (granted in a one-to-many relationship) is the following.

  • Isolate the Ids into an array prior to the Mongoose Query

let ids = []
for (object in query) {
  ids.push(query[object]._id)
}

collection.find({ id : $in : ids }).then((result) => {
  for (let i in result) {
    for (let j in query) {
      if (result[i]._id === query[j]._id) {
        query[j].name = result[i].name
      }
    }
  }
}).catch((error) => {
  console.log("Query Error")
})
  • Also, in the above example, taking the array of Ids is going to require the Mongo $in operator to search through the array and return the appropriate collection items.

I hope this helps!

Nicholas Dullam
  • 291
  • 1
  • 9