Search code examples
node.jsmongodbrestmongoose

fetch all the users with specific attribute


Hey everybody Im new with node and mongo hope for your help with it. I defined a user schema with mongoose:

var userSchema = mongoose.Schema({


local            : {
    email        : String,
    password     : String,
    name         : String
},
facebook         : {
    id           : String,
    email        : String,
    token        : String,
    firstName    : String,
    familyName   : String
},
google           : {
    id           : String,
    email        : String,
    token        : String,
    firstName    : String,
    familyName   : String
}});

Im tring to fetch all the users (from local google and facebook) with specific email. How do I write it ? I tried something like:

var User = require('./models/user');
app.get('/api/user/:email',function(req,res){
    User.findOne({'email':req.params.email},function(err,user){
       res.json(user);
    })
});

How do I fix it ? Thanks.


Solution

  • Add

    module.exports = mongoose.model("User", userSchema);
    

    to your schema file.

    Then try the following:

    var User = require('./models/user');
    app.get('/api/user/:email',function(req,res){
        User.findOne({"local.email": req.params.email}, function(err,user){
            res.json(user);
        });
    });
    

    Or for all three:

    var User = require('./models/user');
    app.get('/api/user/:email',function(req,res){
        User.findOne({$or: [
            {"local.email": req.params.email},
            {"facebook.email": req.params.email},
            {"google.email": req.params.email}
        ]}, function(err,user){
            res.json(user);
        });
    });