1

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"
}
2
  • 1
    What is the NodeJs version you are using? Commented Jan 27, 2018 at 14:15
  • v8.9.4 which is LTS. Do I need node 9.4.0 to use Object.values()? Commented Jan 27, 2018 at 14:35

1 Answer 1

3

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]
})
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the clarification. I opted for option 3 and it worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.