Blank
Blank

Reputation: 443

MongoDB - mapReduce - Object.values is not a function

Here is a document example of my collection:

{
  "_id": "5a68a9308117670afc3522cd",
  "username": "user1",
  "favoriteItems": {
    "5a0c6711fb3aac66aafe26c6": {
      "_id": "5a0c6711fb3aac66aafe26c6",
      "name": "item1",
    },
    "5a0c6b83fd3eb67969316dd7": {
      "_id": "5a0c6b83fd3eb67969316dd7",
      "name": "item2",
    },
    "5a0c6b83fd3eb67969316de4": {
      "_id": "5a0c6b83fd3eb67969316de4",
      "name": "item3"
    }
  }
}

and I am using mongoDB mapReduce feature to count how many times an item is liked by users.

here are my map and reduce functions:

var mapFun = function () {
    Object.values(this.favoriteItems).forEach(item => {
        emit(item, 1)
    })
}

var redFun = function (item, values) {
    count = 0
    for(i = 0; i<values.length; i++) {
        count += values[i]
    }
    return count
}

However, I get the error Object.values is not a function:

2018-01-27T13:58:08.494+0000 E QUERY    [thread1] Error: map reduce failed:{
        "ok" : 0,
        "errmsg" : "TypeError: Object.values is not a function :\n@:2:5\n",
        "code" : 139,
        "codeName" : "JSInterpreterFailure"
}

Upvotes: 1

Views: 1526

Answers (1)

Pubudu Dodangoda
Pubudu Dodangoda

Reputation: 2874

Object.values is a ES2017 feature. Probably your NodeJs version is old and doesn't support the feature.

You can either,

  1. Upgrade NodeJs
  2. Use babel to transpile the code
  3. Use Object.keys and then use the key to refer the value,

like this,

Object.keys(this.favoriteItems).forEach((key)=>{
   let value = this.favoriteItems[key]
})

Upvotes: 3

Related Questions