2015-04-03 29 views
4

我在管道中正在執行Mongoose/MongoDB .aggregate查詢,並使用$limit進行查詢。當我使用一個號碼,如2,它工作正常。如果我設置了一個像testNum = 2這樣的變量,然後做了{$limit: varNum},它工作正常。但是,如果我發送REST查詢並嘗試執行$limit: req.body.show,它表示該值不是數字。'使用req.query.property時,必須將限制指定爲數字'錯誤

我可以看到該值是一​​個通過console.log的數字。管道中的其他查詢不會抱怨他們沒有給出數字。這裏是代碼:

var show = req.query.show, // the number of items to show per page 
    page = req.query.page, // the current page being asked for 
    stream = req.params.stream, // the type of content to get 
    skip = (page > 0 ? ((page - 1) * show) : 0), // amount to skip 
    testNum = 3 

console.log(show + " " + skip + " " + page) 

Content.aggregate([ 
    { $unwind: '$users' }, 
    { $group: { 
     _id: '$_id', 
     title: { $first: '$title' }, 
     description: { $first: '$description' }, 
     images: { $first: '$images' }, 
     url: { $first: '$url' }, 
     saveCount: { $sum: 1 } } 
    }, 
    { $sort: { saveCount: -1 } }, 
    { $skip: skip }, 
    { $limit: show } 
]) 
.exec() 

這裏的查詢是?show=2&page=1。控制檯輸出是2 0 1。這是正確的。

完整的錯誤是在這裏:

{ [MongoError: exception: the limit must be specified as a number] 
name: 'MongoError', 
errmsg: 'exception: the limit must be specified as a number', 
code: 15957, 
ok: 0 } 

回答

5

出於某種原因show被當作在$limit的情況下一個字符串,但沒有其他人似乎介意。我這樣做是爲了解決這個問題,但我認爲這可能是Express或Mongoose/MongoDB的一個bug。如果有人知道在哪裏提出這個問題,請告訴我。

的解決辦法是使用parseInt這樣的:

var show = parseInt(req.query.show), // the number of items to show per page 
0

可以使用一元+操作了。 +req.query.show

相關問題