1

I have some product data where some product don't have key "images.cover". now when I try to print all data it show error

Cannot read property 'cover' of undefined.

So I try to make if images.cover key not present then just put var cover = ''; else images.cover value. I'm using nodejs and mongodb

Konrad Krakowiak
  • 12,285
  • 11
  • 58
  • 45
Himanshu
  • 85
  • 1
  • 8
  • possible duplicate of [Check that Field Exists with MongoDB](http://stackoverflow.com/questions/19868016/check-that-field-exists-with-mongodb) – Neo-coder Apr 10 '15 at 11:23
  • just write if(images.cover !== undefined) { // do here } else { var cover = '';} – Dineshaws Apr 10 '15 at 11:24

1 Answers1

0

From the error message:

Cannot read property 'cover' of undefined

you can narrow down the error source on the trouble product document to any of the three attributes:

  1. the document doesn't have images field (hence the undefined object),
  2. the images field may be null, and
  3. the covers key may not be present as well.

Let's consider a minimum test case where a sample collection has documents with the above three + one with the images.cover key set:

db.product.insert([
    /* 0 */
    {
        "_id" : 1,
        "image" : {
            "cover" : "test1",
            "url" : "url1"
        }
    },

    /* 1 */
    {
        "_id" : 2,
        "image" : {
            "url" : "url2"
        }
    },

    /* 2 */
    {
        "_id" : 3
    },

    /* 3 */
    {
        "_id" : 4,
        "image" : {
            "cover" : null,
            "url" : "url4"
        }
    }
]);

In mongo shell you can check to see if a key is present or not either by using native JavaScript methods or using mongodb's $exists operator. For the former, you could try:

var cover = "", covers = [];
db.product.find().forEach(function (doc){    
    var cover = "";
    if ((doc.image !== undefined) && (typeof(doc.image.cover) !== "undefined") && (doc.image.cover !== undefined)){
        cover = doc["image"].cover;        
    }  
    covers.push(cover);     
});
print(covers); /* will print to mongo shell:
{
    "0" : "test1",
    "1" : "",
    "2" : "",
    "3" : null
}
*/

Using $exists operator with its value set to true, this searches for documents that contain the field, including documents where the field value is null. So using this route is probably not going to work in your example since you would like to assign the covers variable for unmatched documents as well:

var cover = "", covers = [];
db.product.find({ "image.cover": {$exists : true} }).forEach( function(doc) { 
    covers.push(doc["image"].cover);
});
print(covers); /* this will print to mongo shell:
{
    "0" : "test1",
    "1" : null
}
*/
chridam
  • 100,957
  • 23
  • 236
  • 235