2015-11-19 58 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