【问题标题】:Mongoose find returns empty array (works fine for other collections)Mongoose find 返回空数组(适用于其他集合)
【发布时间】:2015-11-19 20:50:00
【问题描述】:

我在 nodejs 中编写了一个宁静的 api,大部分情况下都相当成功。我正在访问的 MongoDB 中有两个集合返回空字符串,并且恰好是唯一在其名称中包含大写字母的集合。当我使用 MongoClient 时,我可以很好地访问这些集合,所以我知道它不是一个过时的 mongodb 驱动程序。

一个例子是当我尝试访问一个名为 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);
        });
      })
    });

任何建议将不胜感激,谢谢。

【问题讨论】:

    标签: node.js mongodb find capitalization empty-list


    【解决方案1】:

    如果无法针对您的数据库进行测试,则很难回答。但我会尝试一些事情。

    1. 重构 {'storeLicense': req.params.license, 'availableForSale': true} 在查询之外创建对象,然后在将该对象传递给查询之前通过控制台记录该对象。这将确保一切都如您所愿。

    2. 删除“sourceLicense 数量 strainName priceProfile”作为 BulkBuds.find 的第二个参数,并替换为空对象。我通常使用以下语法 {_id:1,quantity:0} 传递一个对象作为第二个参数来修改投影。您的语法可能有效,但以防万一我尝试运行查询而不查看是否产生任何结果。

    3. 确认数据库中的数量确实是数字而不是字符串。我知道猫鼬不会让你插入不验证的记录,不确定查询。很可能不是问题,但验证也无妨。

    4. 创建 Bulkbirds 架构后,试试这个:

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

    另一个远景,但也许它与 mongoose 将集合名称复数有关。使用上述语法将确保它正在查询 bulkBuds 集合。

    再一次,如果不进行测试就很难确定,但希望这些想法能有所帮助。

    【讨论】:

    • 感谢您的回复。这是很好的建议,不幸的是我已经采取了这些步骤,但我非常感谢你的帮助。
    • 嗯,我添加了 4 号,不确定这是否有帮助,但值得一试。文档可以在这里找到。 mongoosejs.com/docs/models.html
    • 奇怪的是,console.log 语句修复了它。这可能是一个同步问题。
    • mongoose.model('bulkBuds', BulkBudsSchema, 'bulkBuds');节省一天
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    • 2012-08-30
    • 2015-10-18
    • 2019-04-28
    • 1970-01-01
    • 2016-05-01
    相关资源
    最近更新 更多