How do I perform a query in Mongoose?


Question

> 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 });
});
1
10
4/28/2011 5:33:39 AM

Accepted Answer

Try this :

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

or

User.findOne( { fb.gender : "male" } )
8
4/28/2011 5:26:31 AM

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

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon