我在 Nodejs 中编写了一个 RESTful 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);
Controller 在查询中有一些多余的逻辑,但简单的查找也会返回一个空字符串。
//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);
});
})
});
如有任何建议,我们将不胜感激,谢谢。
最佳答案
如果无法针对您的数据库进行测试,则很难回答。但我会尝试一些事情。
重构 {'storeLicense': req.params.license, 'availableForSale': true} 以在查询外部创建对象,然后在将对象传递给查询之前控制台记录该对象。这将确保一切都如您所愿。
删除“sourceLicense数量trainName价格Profile”作为BulkBuds.find的第二个参数,并替换为空对象。我通常使用以下语法 {_id:1,quantity:0} 传递一个对象作为第二个参数来修改投影。您的语法可能有效,但以防万一我会尝试运行查询而不查看是否产生任何结果。
确认数据库中的数量确实是数字而不是字符串。我知道 Mongoose 不会让你插入不验证的记录,不确定查询。很可能不是问题,但验证一下也没什么坏处。
创建 Bulkbirds 架构后尝试以下操作:
mongoose.model('bulkBuds', BulkBudsSchema, 'bulkBuds');
另一个远景,但也许与 mongoose 复数集合名称有关。使用上述语法将确保它正在查询bulkBuds集合。
再一次,如果无法测试就很难确定,但希望这些想法能有所帮助。
关于node.js - Mongoose find 返回空数组(适用于其他集合),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33814118/