configure populated data after saving in mongoose

I am working on user signup with nodejs and mongo db , problem is when i inserted all data into collection it's returning all the data in the document i want to restrict some of objects in returning data for example in below example in user object password in included which i should restrict ,

newUser =  new UserSchema({
   firstName : firstName,
   middleName : middleName,
   lastName : lastName,
   email : email,
   location : location,
   password : password,
   createdDate :new Date(Date.now()).toISOString(),
   role : "user"
})
password : { // in scehma
   type: String,
    select :false,
    hide: true,
    required:true
 },
newUser.save((err,user) => {
    if(err){
        return false;
    }else{
        return user ; // user object should not have password in this 
    }
});

Upvotes: 0

Views: 261

Answers (3)

Pavan Vora
Pavan Vora

Reputation: 1734

What you can do is before returning this user you can delete the password filed from that. Like below

newUser.save((err,user) => {
    if(err){
        return false;
    }else{
        user = user.toObject();
        delete user.password;
        return user ; // Now user object do not have password field 
    }
});

Upvotes: 0

mongoose-hidden this plugin helped me , but anyway select:false should work , if not else after long try you can use above plugin

Upvotes: 0

Vaibhav Patil
Vaibhav Patil

Reputation: 2973

Just put select:false with password field where you defined schema.

like :

password : {type : String, select : false}

so it will not return password filed.

Upvotes: 2

Related Questions