2
votes

I'm using two schemas for users. One that contains the password/salt, one that doesn't for returning to the front end. When I use the model that uses the schema WITHOUT the password, it still returns the password :/

Generic User (For sending to the client)

module.exports = {    
    username: String,
    email: String,
    firstName: String,
    lastName: String,
    createdOn: Date,
    updatedOn: Date,
    scopes: [String]
}

Auth User (for creating/updating/authenticating users)

module.exports = {    
    username: String,
    email: String,
    password: String,
    salt: String,
    firstName: String,
    lastName: String,
    createdOn: Date,
    updatedOn: Date,
    scopes: [String]
}

Creating the models with

var modelInstance = mongoose.model("authUser", authUserSchema, 'users')

(in a different file)

var modelInstance = mongoose.model("user", userSchema, 'users')

modelInstance is exported with module.exports = modelInstance;

Update This question answers mine. How to protect the password field in Mongoose/MongoDB so it won't return in a query when I populate collections?

1
Are you persisting both of these? i.e. two entries for each user ?sinanspd
Well both models represent the same collection users It is going to return you the fields whichever model u execute the query from. To restrict the field there are various ways prevent select the password field when you query from Model of userSchema. Also assuming that you are following One schema/model per file structure in nodeambianBeing
@ambianBeing That link was what I needed. I just wasn't searching for the right thing earlier :( But it's good to have variations of questions like this b/c not everyone will approach the problem the same.cphilpot

1 Answers

0
votes

You don't have a clear question, but I guess you are asking if you can restrict it. The answer is 'no' by default.

There is a plugin for this: https://www.npmjs.com/package/mongoose-strictmodel But it's really out of date.

It's easy enough though to create a wrapper function:

function safeUser(userModel) {
  return {
    username: userModel.username,
    email: userModel.email,
    firstName: userModel.firstName,
    lastName: userModel.lastName,
    createdOn: userModel.createdOn,
    updatedOn: userModel.updatedOn,
    scopes: userModel.scopes
  }
}