Mongoose selects only fields explicitly declared in the schema

When using Mongoose and database queries by default, all fields are selected, and I must explicitly tell Mongoose which fields I do not want to select, for example, if I do not need a field user, I must do:

var schema = new Schema(
    {
    insertedAt: {type: String},
    tags: {type: String},
    user: {type:Object, select:false},
    connectedIds: {type:Array}
    }

The problem is that fields can be added to the database without the developer API (s) being aware of this.

Is it possible to tell Mongoose to only select fields that are explicitly set?

+4
source share
1 answer

A workaround always selects only the fields defined in yours Schema. What you need to do is get all the fields with the property pathsand pass it to the operator select(), for example:

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

//and when execute a query
YourModel.find({}).select(fields).exec(callback);

, - , . , .

+4

All Articles