0

I have a password and salt stored in mongodb, I can query all other fields except the salt.

Here is the schema:

var userSchema = new Schema({
firstname     : { type: String, trim: true},
lastname      : { type: String, trim: true},
email         : { type: String, required: true, unique: true, trim:true},
password      : { type: String, required: true},
salt          : { type: String, required: true, trim: true, unique: true},
addedOn       : { type: String, required: false}
});
...

And the request for a doc here:

User.findOne({
    email: req.body.email   
}).exec(function(err, obj) {
    if (err) {
        console.log("MongoDB Error: " + err);
        return res.status(500); // or callback
    } 
    else if (obj) {
        console.log(obj.firstname); //This works
        console.log(obj.salt); // And this doesn't
    }
});

But when I run db.users.find() from terminal, this doc exists and has a salt.

EDIT:

I found the solution to my problem here How to protect the password field in Mongoose/MongoDB so it won't return in a query when I populate collections?

Community
  • 1
  • 1
Siya Mzam
  • 4,655
  • 1
  • 26
  • 44

2 Answers2

1

using this you can force mongoose to query and return a certain field from a mongodb collection:

User.findOne({
 email: req.body.email  
},
{ firstname: 1, lastname: 1 , email: 1, password: 1, addedOn: 1}).exec(function(err, obj) {
if (err) {
console.log("MongoDB Error: " + err);
 return res.status(500); // or callback
} 
else if (obj) {
console.log(obj);
});
Mital Gajjar
  • 244
  • 1
  • 6
0

I like Mital's answer, it retrieves the field but for some reason the returned value is not usable.

This worked rather.

User.findOne({
     email: req.body.email 
}).select('+salt').exec(function(err, obj)
{ ... }
Siya Mzam
  • 4,655
  • 1
  • 26
  • 44