Danielle Isquierdo Danielle Isquierdo - 5 months ago 27
Node.js Question

Mongoose find by field?

I'm using mongoDb and mongoose with nodejs (express) and everything works fine, except for this function:



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

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

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

});

});





It brings back an empty array in promo, but I do have documents in my db.

The problem seems to be with the field active in "{active:"true"}". When I look for documents without any filter (with "find({},...") it works fine.

When I run db.promotions.find({active: "true"}) in mongo it works.

This is my promotion schema:



// 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;





This is what I get in mongodb:

enter image description here

I've tried every possible formats of {active:true} ({"active":"true"}, {"active":true}, etc..) and nothing works.

Answer

The data types of the fields as defined in your schema have to match the data types of the fields in the document.

So because active is a string in your documents, you need to define it as string in your schema as well:

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

Otherwise, with active defined as a Boolean in your schema, Mongoose will cast any active value in your query to either true or false, which won't match the 'true' and 'false' string values in your docs.

Of course, if active actually should be a boolean in your docs, then you need to update all your docs so that they match your existing schema. This would be preferable to using string values for booleans.

Comments