shamant
shamant

Reputation: 57

looping through array document in mongodb

I have a MongoDB document called cartItems, which is an array.

"cartItems" : [    

    {
         "productID" : "2ae6b8013ade44ac60de872f",
        "quantity" : 5
    }, 

    {
        "productID" : "1ae2b8013ade32ac60de872d",
        "quantity" : 5
    },

    {
        "productID" : "6ae9b8023ade44ac60de8732",
        "quantity" : 5
    }, 

    {
        "productID" : "3ae9b96d3ade43ac60de8734",
        "quantity" : 5
    }
]

Now, I want to loop through it and obtain the values of "productID". I tried using .length (realized later it was a pretty noob thing to do) and it gave only the first productID.

  var user = Cart.find({"_id":Meteor.userId()}).fetch()[0];
      for(i=0;i<user.cartItems.length; i++){
          var id = new Mongo.ObjectID(user.cartItems[i].productID);
          console.log(id);
      }

I also tried using $size, but since my document is a dynamic array, I can't know how many products are in it before hand.

Help would be appreciated.

Upvotes: 2

Views: 4467

Answers (2)

Calvin Nunes
Calvin Nunes

Reputation: 6516

well, I don't have any experience with mongoDB, but here's an example of how to loop through each element of an object:
(I understood that your problem is the loop, if not, please tell me)

var user ={ "cartItems": [  
    {
      "productID": "2ae6b8013ade44ac60de872f",
      "quantity": 5
    }, 
    {
      "productID": "1ae2b8013ade32ac60de872d",
      "quantity": 5
    },
    {
      "productID": "6ae9b8023ade44ac60de8732",
      "quantity": 5
    }, 
    {
      "productID": "3ae9b96d3ade43ac60de8734",
      "quantity": 5
    }
]}

var cartItems = user.cartItems;
for (var item of cartItems){
   let id = item.productID;
   console.log("Id: " + id);
}

Probably, with mongo you can do in the same way, like this, using for..of :

var user = Cart.find({"_id":Meteor.userId()}).fetch()[0];
for(var item of user.cartItems){
   let id = new Mongo.ObjectID(item.productID);
   console.log(id);
}

Sorry if i'm saying bullshit here, because as I said, I have no experience in mongo, but maybe this helps...

Upvotes: 1

Senthur Deva
Senthur Deva

Reputation: 787

try it in mongo shell or robomongo

 var user = db.col.find({}).toArray()[0];
 for(i=0;i<user.cartItems.length; i++){
    printjson(ObjectId(user.cartItems[i].productID));
 }

Upvotes: 0

Related Questions