2016-05-06 37 views
0
mr = db.runCommand({ 
    "mapreduce" : "company", 
    "map" : function() { for (var key in this) { emit(key, null); } }, 
    "reduce" : function(key, stuff) { return null; }, 
    "out": "company" + "_keys" 
}) 

db[mr.result].distinct("_id") 

這是我用來從mongodb獲取密鑰的查詢,但是如何將此查詢轉換爲打開js代碼?誰能幫我?通過使用帆獲取mongodb鍵js

回答

1

在您的模型上使用native()方法訪問底層Mongo集合,然後執行像mapReduce這樣的原始Mongo查詢。下面演示了這一點:

Company.native(function(err, companyCollection) { 
    if (err) return res.serverError(err); 

    // Map function 
    var map = function() { for (var key in this) { emit(key, null); } }; 
    // Reduce function 
    var reduce = function() { }; 
    // Other options 
    var options = {out: {replace : 'company_keys'}}; 

    // Peform the map reduce 
    // Mapreduce returns the company_keys collection with the results 
    companyCollection.mapReduce(map, reduce, options, function(err, keysCollection) { 
     // Perform a distinct query against the _id field of the keysCollection 
     keysCollection.distinct("_id", function(err, results) { 
      if (err) return res.serverError(err); 
      console.log(results); // returns a list of the keys ['key1', 'key2', ...] 

      return res.ok(results);   
     }); 
    }); 
}); 
+0

感謝給瞭解決方案#chridam但使用此代碼我收到錯誤:「non_object_property_call 消息:無法調用未定義的方法‘不同’」? – sriteja

+0

@sriteja我已經更新了我的答案 – chridam

+0

感謝chridam它正在成功工作 – sriteja