How do I perform a query in Mongoose?

> db.users.findOne();
{
    "_id" : ObjectId("4db8ebb4c693ec0363000001"),
    "fb" : {
        "name" : {
            "last" : "Sss",
            "first" : "Fss",
            "full" : "Fss"
        },
        "updatedTime" : "2011-04-27T09:51:01+0000",
        "verified" : true,
        "locale" : "en_US",
        "timezone" : "-7",
        "email" : "abc@gmail.com",
        "gender" : "male",
        "alias" : "abc",

        "id" : "17447214"
    }
}

So that's my Mongo object. Now i want to find it via Mongoose:

User.findOne( { gender: "male" }, function(err, docs){
    console.log(err);  //returns Null
    console.log(docs);  //returns Null.
});

That doesn't work! Neither does this:

User.findOne( { fb: {gender:"male"} }, function...

Null, null.

This is my entire thing:

app.get('/:uid',function(req,res){
    params = {}
    User.findOne({ $where : "this.fb.gender == 'male' " }, function(err, docs){
        console.log(docs);
    });
    res.render('user', { locals:params });
});

Answers


Try this :

User.findOne( { $where : "this.fb.gender == 'male' " } )

or

User.findOne( { fb.gender : "male" } )

I'm one of the authors of mongoose. You can do this query in one of several ways:

  • find syntax

    User.findOne({'fb.gender': 'male'}, callback);
    
  • where syntax

    User.where('fb.gender', 'male').findOne(callback);
    
  • named scope syntax

    UserSchema.namedscope('male').where('fb.gender', 'male');
    // ...
    var User = mongoose.model('User', UserSchema);
    
    // Now you can write queries even more succinctly and idiomatically
    User.male.findOne(callback);
    

Need Your Help

How can I get all the doc ids in MongoDB?

mongodb

How can I get an array of all the doc ids in MongoDB? I only need a set of ids but not the doc contents.

Python: why does `random.randint(a, b)` return a range inclusive of `b`?

python random

It has always seemed strange to me that random.randint(a, b) would return an integer in the range [a, b], instead of [a, b-1] like range(...).