Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" : "[email protected]",
        "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 });
});
like image 502
TIMEX Avatar asked Apr 28 '11 05:04

TIMEX


People also ask

What is a query in Mongoose?

The Mongoose Query class provides a chaining interface for finding, updating, and deleting documents.

What is done () in Mongoose?

It just means that your new document will have a field with "done" as key and "false" boolean as value.

What does exec () do Mongoose?

exec() function returns a promise, that you can use it with then() or async/await to execute a query on a model "asynchronous".


1 Answers

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);
    
like image 87
Brian Noguchi Avatar answered Oct 15 '22 06:10

Brian Noguchi