在 mongodb 中遍历数组文档

looping through array document in mongodb

我有一个名为 cartItems 的 MongoDB 文档,它是一个数组。

"cartItems" : [    

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

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

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

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

现在,我想遍历它并获取 "productID" 的值。 我尝试使用 .length(后来意识到这是一件非常菜鸟的事情)并且它只给出了第一个 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);
      }

我也试过使用$size,但是由于我的文档是一个动态数组,我无法事先知道里面有多少产品。

不胜感激。

在 mongo shell 或 robomongo

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

好吧,我对 mongoDB 没有任何经验,但这里有一个如何遍历对象的每个元素的示例:
(我知道你的问题是loop,如果没有请告诉我)

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);
}

也许,使用 mongo 你可以用同样的方式做,像这样,使用 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);
}

对不起,如果我在这里说废话,因为正如我所说,我没有 mongo 方面的经验,但也许这会有所帮助...