首页 文章

猫鼬发现了?

提问于
浏览
3

我正在使用mongoDb和mongoose与nodejs(express),一切正常,除了这个函数:

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

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

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

    });

});

它在promo中带回一个空数组,但我的db中有文档 .

问题似乎是“{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}等)的所有可能格式,但没有任何效果 .

2 回答

  • 4

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

    因为 active 是文档中的字符串,您还需要在模式中将其定义为字符串:

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

    否则,将 active 定义为架构中的 Boolean ,Mongoose会将查询中的任何 active 值转换为 truefalse ,这与您文档中的 'true''false' 字符串值不匹配 .

    当然,如果 active 实际上应该是您的文档中的布尔值,那么您需要更新所有文档,以便它们与您现有的架构匹配 . 这比使用布尔值的字符串值更可取 .

  • 0

    您需要等待订阅加载,尤其是在根(默认)路由 . 尝试将查找移动到 index 模板中的帮助程序,并将其(或布局)包装在响应 {{#if Template.subscriptionsReady}} 块中

    也可以看看:

    https://www.discovermeteor.com/blog/template-level-subscriptions/

相关问题