Mongoose按字段查找?

3

我正在使用Node.js(express)中的mongoDb和mongoose,除了这个函数之外,一切都正常:

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}等),但都不起作用。


我认为 db.Promotions.find() 只会返回空值!检查一下吧! - gu mingfeng
2个回答

5

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

因此,由于在您的文档中 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确实应该是布尔值,则需要更新所有文档以使其与现有模式匹配。这比使用布尔值的字符串更可取。

非常感谢!那就是问题所在。我将我的文档更改为布尔类型在mongoDB中,因为它们本来就应该是这样的。 - Danielle Isquierdo

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接