0

I'd like to use one collection for two schemas E.g: Document in DB:

{
  "name":"John",
  "position":"CEO"
}

Schema User:

{
  "name" : String
}

Schema Employee:

{
  "name" : String,
  "position" : String
}

Nevertheless, when selecting a user (User.findById()) in the result I can see all the fields from the document, even not defined in the schema. I don't want to disclose some fields in a stripped-down model at all so select: false for such fields is not what I'm looking for ... Also, I'd like to prevent saving any fields not listed in a schema.

Is it possible to define a schema in such way?

Or I'm wrong and select:false is exactly what I'm looking for? :-)

I'm using Mongoose 5.0.14 but it is not a problem to update to the latest version if it would help.

I saw question How to select a single field in MongoDB?, but I want ODM to do this for me.

RidgeA
  • 1,506
  • 1
  • 10
  • 18
  • Possible duplicate of [How to select a single field in MongoDB?](https://stackoverflow.com/questions/25589113/how-to-select-a-single-field-in-mongodb) – Ashh Jul 06 '18 at 06:22

2 Answers2

0

Try this. :)

var fields = Object.keys(yourSchema.paths).join(' ');

//and when execute a query
User.find({}).select(fields).exec(callback);
UtkarshPramodGupta
  • 7,486
  • 7
  • 30
  • 54
0

try this in your schema

 MySchema.pre('find', function() {
    this.select(fileds);
});
Kaushik Makwana
  • 2,422
  • 9
  • 31
  • 50