2015-11-19 102 views
1

我一直在nodejs中大多數情況下都相當成功地寫了一個restful api。 MongoDB中有兩個我正在訪問的集合,它們返回空字符串,並且恰好是名稱中包含大寫字母的唯一集合。當我使用MongoClient時,我可以很好地訪問這些集合,所以我知道它並不是過時的mongodb驅動程序。Mongoose查找返回空數組(適用於其他集合)

一個例子是,當我試圖訪問一個集合稱爲bulkBuds

//bulkBuds model 

var mongoose = require('mongoose'), 
    Schema = mongoose.Schema; 

var BulkBudsSchema = new Schema({ 
    sourceLicense: String, 
    quantity: Number, 
    strainName: String, 
    priceProfile: String 
}); 

mongoose.model('bulkBuds', BulkBudsSchema); 

控制器具有查詢有點多餘的邏輯,而是一個簡單的查找返回一個空字符串爲好。

//bulkBuds controller 
var express = require('express'), 
    router = express.Router(), 
    mongoose = require('mongoose'), 
    BulkBuds = mongoose.model('bulkBuds'), 
    Friends = mongoose.model('Api'), 
    config = require('../../config/config'), 
    jwt = require('express-jwt'); 

    module.exports = function (app) { 
     app.use('/api/bulkBuds/', router); 
    }; 

    router.get('/:license', jwt({secret: config.secret}), function (req, res, next) { 
     if(!req.user.friend){ 
     res.status(401); 
     } 
     Friends.findById(req.user.id, function(err, friend){ 
     if(err) throw err; 
     if(!friend) res.send("friend does not exist"); 
     if(req.user.username != friend.username) res.send("invalid user"); 
     console.log(req.params.license); 
     console.log(BulkBuds.find({})); 
     BulkBuds.find({'storeLicense': req.params.license, 'availableForSale': true}, 
     "sourceLicense quantity strainName priceProfile", function (err, bulkBuds) { 
      if (err) return next(err); 
      console.log(bulkBuds); 
      res.send(bulkBuds); 
     }); 
     }) 
    }); 

任何建議將不勝感激,謝謝。

回答

2

如果不能對數據庫進行測試,很難回答。但我會嘗試一些事情。

  1. 重構{「storeLicense」:req.params.license,「availableForSale」:真}創建對象的查詢外,然後控制檯日誌之前將它傳遞到查詢該對象。這將確保一切如你所願。

  2. 刪除「sourceLicense數量strainName priceProfile」作爲BulkBuds.find的第二個參數,並替換爲空對象。我通常使用以下語法{_id:1,quantity:0}傳遞一個對象作爲第二個參數來修改投影。你的語法可能工作,但以防萬一我會嘗試運行查詢,而不看看是否會產生任何結果。

  3. 確認您的數據庫中的數量確實是一個數字而不是一個字符串。我知道貓鼬不會讓你插入不確認的記錄,不確定是否有疑問。最有可能不是這個問題,但不傷害覈實。

  4. 創建Bulkbirds模式後試試這個:

mongoose.model( 'bulkBuds',BulkBudsSchema, 'bulkBuds');

另一個長鏡頭,但也許它與貓鼬複合集合名稱有關。使用上面的語法將確保它查詢bulkBuds集合。

再一次,如果不能測試就很難查明,但希望這些想法能夠幫助。

+0

感謝您的回覆。這很好的建議,不幸的是我已經採取了這些步驟,但我非常感謝你的幫助。 – user3073234

+0

嗯,我加了4號,不知道這是否會幫助,但值得一試。文檔可以在這裏找到。 http://mongoosejs.com/docs/models.html – user2263572

+0

奇怪的是一個console.log語句修復了它。這可能是一個同步問題。 – user3073234