2016-06-13 103 views
2

我使用的MongoDB和猫鼬用的NodeJS(表达),一切工作正常,除了这个功能:猫鼬按字段查找?

router.get('/', function(req, res, next) { 
 

 
    promotions.find({active:"true"},function(err,promo){ 
 
     if (err) throw err; 
 

 
     res.render('index', 
 
      { 
 
       promos: promo 
 
      }); 
 

 
    }); 
 

 
});

它带回在促销空数组,但我有文件在我的数据库。

该问题似乎与“{active:”true“}”中的字段激活有关。当我查找没有任何过滤器的文档时(使用“find({},...”)它工作正常。

当我运行mongo中的db.promotions.find({active:“true”}) 。

这是我的推广模式:

// grab the things we need 
 
var mongoose = require('mongoose'); 
 
var Schema = mongoose.Schema; 
 

 
// create a schema 
 
var promotionSchema = new Schema({ 
 
    title: String, 
 
    subtitle: String, 
 
    url: String, 
 
    image: String, 
 
    active: 
 
     { 
 
      type: Boolean, 
 
      default: false 
 
     } 
 
}); 
 

 
var Promotion = mongoose.model('Promotion', promotionSchema, 'promotions'); 
 

 
// make this available to our Node applications 
 
module.exports = Promotion;

这是我在MongoDB中得到:

enter image description here

我试过{active:true}({“active”:“true”},{“active”:true})等各种可能的格式,并且没有任何效果。

+0

我认为db.Promotions.find()将返回空!核实! –

回答

3

字段的数据类型定义你的模式必须与文档中字段的数据类型相匹配。

是因为active是在文档中的字符串,你需要将它定义为架构中的字符串,以及:

var promotionSchema = new Schema({ 
    title: String, 
    subtitle: String, 
    url: String, 
    image: String, 
    active: 
     { 
      type: String, 
      default: 'false' 
     } 
}); 

否则,定义为架构中的一个Booleanactive,猫鼬会施放任何active查询中的值为truefalse,这与您的文档中的'true''false'字符串值不匹配。

当然,如果active实际上应该在你的文档一个布尔值,那么你需要让他们配合您现有的模式来更新您的所有文档。这比使用布尔值的字符串值更好。

+0

非常感谢!这是问题所在。我在mongoDB中将文档更改为布尔值,因为这是他们本来应该首先考虑的。 –

+0

为我工作,谢谢! –