将范围传递给db.collection.group

时间:2016-01-17 14:59:15

标签: node.js mongodb

是否可以传递全局背景db.collection.group' keyf

{MongoClient} = require 'mongodb'

GLOBAL_VAR = 1

reducer = (obj, prev) -> prev.count += GLOBAL_VAR
initial = {count:0}

MongoClient.connect 'mongodb://localhost:27017/test', (err, db) ->
  throw err if err
  db.collection('orders').group [], {}, initial, reducer, (err, result) ->
    throw err if err
    console.log result

我收到以下错误

MongoError: exception: ReferenceError: GLOBAL_VAR is not defined at $group reduce setup:2

1 个答案:

答案 0 :(得分:1)

您可以将变量作为初始状态传递

{MongoClient} = require 'mongodb'

GLOBAL_VAR = 1

reducer = (obj, prev) -> prev.count += prev.GLOBAL_VAR
initial = {count: 0, GLOBAL_VAR}

MongoClient.connect 'mongodb://localhost:27017/test', (err, db) ->
  throw err if err
  db.collection('orders').group [], {}, initial, reducer, (err, result) ->
    throw err if err
    console.log result