MongoDB和Mongoose:无法检索数据

时间:2015-07-02 21:34:24

标签: node.js mongodb mongoose

我是Mongoose的新手,在收集数据时遇到问题。

router.js
---------
router.post('/api/v1/cars-by-type', cars.getCarsByType);
router.get('/api/v1/car-criteria', cars.getCarCriteria);

cars.js
-------
var mongoose = require('mongoose');
mongoose.connect(mongodb://[somehost]/[somedb]);

var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;

var carSchema = new Schema({
  id: ObjectId,
  key: String,
  make: String,
  model: String,
  submodel: String,
  year: String,
  name: String,
  type: String,
  values: {
    price: Number,
    fuel_eff: Number,
    performance: Number,
    comfort: Number,
    condition: Number,
    safety: Number
  },
  image: String
});
var Car = mongoose.model('Car', carSchema);

var carCriteriaSchema = new Schema({
  key: String,
  full_name: String,
  type: String,
  is_objective: Boolean,
  goal: String
})
var Criteria = mongoose.model('Criteria', carCriteriaSchema);

var getCarsByType = function (req, res) {
  Car.find({'type':{$in:req.body.type}}, function (err, data) {
    if(err) {
        console.log("Error in getting car: " + JSON.stringify(err));
        res.send("Error in getting car: " + err);
    }

    console.log("Car data: " + JSON.stringify(data));
    res.send(data);
  });
}

var getCarCriteria = function (req, res) {
  Criteria.find({'key':'performance'}, function (err, carCriteria) {
    if(err) {
        console.log("Error in getting car-criteria: " + JSON.stringify(err));
        res.send("Error in getting car-criteria: " + err);
    }

    console.log("Car-criteria: " + JSON.stringify(carCriteria));
    res.send(carCriteria);
  })
}

module.exports = {
  getCarsByType: getCarsByType,
  getCarCriteria: getCarCriteria
}

在cars.js中,函数" getCarsByType"工作正常,返回的所有数据(使用Postman测试)与使用mongodb shell命令获得的数据相匹配。

然而" getCarCriteria"不断返回空数据 从控制台:

Car-criteria: []

这是使用mongo shell的标准集合的示例查询:

rs-ds049570:PRIMARY> db.criteria.find({'key':'performance'}).pretty()
{
  "_id" : ObjectId("54f4f3f574c2b4daef744be8"),
  "key" : "performance",
  "full_name" : "Performance",
  "type" : "NUMERIC",
  "is_objective" : false,
  "goal" : "MAX"
}

感谢任何见解。

1 个答案:

答案 0 :(得分:0)

试试这个:

var Criteria = mongoose.model('Criteria', carCriteriaSchema, 'criteria');

Mongoose将集合名称复数为'标准'。所以你需要指定实际的集合名称。 See doc