Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Querying other collection inside forEach

I want to do something like:

db.ratings.find().forEach(function(doc){

  var item = db.items.find({_id: doc.item_id})
  var ry = item.detail.ry
  db.ratings.update(doc,{$set: {itd: ry}})

})

The problem is that db.items.find({_id: doc.item_id}) is returning something to which I cannot call document properties directly. Which would it be the correct way of doing this? Thanks!

db.items:

{
    "_id" : ObjectId("5461c8f0426f727f16000000"),
    "n" : "The Shawshank Redemption",
    "detail" : {
      "ry": 1992
    }
}
like image 834
borjagvo Avatar asked Dec 02 '14 18:12

borjagvo


1 Answers

The find() function returns a cursor, you need to iterate it:

When the find() method “returns documents,” the method is actually returning a cursor to the documents

Your code, updated:

db.ratings.find().forEach(function(doc){

  db.items.find({_id: doc.item_id}).forEach(function(item){
   var ry = item.detail.ry;
   db.ratings.update(doc,{$set: {itd: ry}});
   })
})

or you may use findOne() which returns one of the matching documents.

db.ratings.find().forEach(function(doc){

  var item = db.items.findOne({_id: doc.item_id})
  var ry = item.detail.ry
  db.ratings.update(doc,{$set: {itd: ry}})

})
like image 85
BatScream Avatar answered Nov 21 '22 23:11

BatScream