2016-02-20 82 views
0

原來在Node.js的MongoDB中一個有趣的錯誤,如果我把下面的表格驅動本地查詢問題:MongoDB中的NodeJS

locals.collection.find(filter, req.query); 

返回我以下錯誤:

MongoError: query selector must be an object 

現在,如果我手動將查詢工作。 我有這個問題很長一段時間,我嘗試了幾種方法。

locals.collection.find({slug:'somak'}, req.query); 

我使用下列的函數:

exports.findAll = function(req, res, next) { 

    var locals = {}, 
     section = req.params.section, 
     query = req.query, 
     filter = {}; 

    if(query.filter) { 

     filter = query.filter.replace(/"(\w+)"\s*:/g, '$1:'); 
     filter = filter.replace(/["]/g, "'"); 

    } 

    console.log(filter); 


    delete query.filter; 

    async.series([ 

     function(callback) { 
      MongoClient.connect(url, function(err, db) { 
       if (err) return callback(err); 
       locals.collection = db.collection(section); 
       callback(); 
      }); 
     }, 

     function(callback) { 
      locals.collection.count(filter, function (err, result){ 
       if (err) return callback(err); 
       locals.count = result; 
       callback(); 
      }); 
     }, 

     function(callback) { 

      var cursor = locals.collection.find({slug:'somak'}, req.query); 

      if(req.query.page) { 
       cursor = cursor.skip(Math.abs(req.query.limit) * --req.query.page); 
      } 

      cursor.toArray(function(err, docs) { 
       if (err) return callback(err); 
       locals.docs = docs; 
       callback(); 
      }); 
     } 
    ], 

    function(err) { //This function gets called after the three tasks have called their "task callbacks" 
     if (err) return next(err); 
     // Here locals will be populated with 'count' and 'docs' 
     res.json({ 
      count: locals.count, 
      data: locals.docs 
     }); 
    }); 
+0

的console.log(過濾器)的'值''是{{蛞蝓: 'somak'}}'? 「req.query」的價值是什麼? – zangw

+0

查詢:{filter:'{「title」:「Test」}',限制:'5',頁面:'1',排序:' - 發佈'} –

回答

0

只需使用JSON.parse:

exports.findAll = function(req, res, next) { 

    var locals = {}, 
     section = req.params.section, 
     query = req.query, 
     filter = {}; 

    if(query.filter) { 
     filter = JSON.parse(query.filter); 
    } 

    delete query.filter; 

...