Mongoose仅选择在Schema中显式声明的字段

Dav*_*ino 4 mongoose

当使用Mongoose并查询数据库时,默认选择所有字段,我必须明确告诉Mongoose我不想选择哪些字段,例如,如果我不想要字段 user我应该做:

var schema = new Schema(
    {
    insertedAt: {type: String},
    tags: {type: String},
    user: {type:Object, select:false},
    connectedIds: {type:Array}
    }
Run Code Online (Sandbox Code Playgroud)

问题是,如果没有API开发人员(我)知道它,可能会将字段添加到数据库中.

有可能告诉Mongoose 选择明确设置的字段吗?

Rod*_*ros 5

有一种解决方法,始终只选择您的中定义的字段Schema.您需要做的是获取具有schema paths属性的所有字段并将其传递给您的select()语句,如:

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

//and when execute a query
YourModel.find({}).select(fields).exec(callback);
Run Code Online (Sandbox Code Playgroud)

这样,即使有人向您的对象添加了一个新字段,它也永远不会被显示出来.缺点是您必须为每个查询执行此操作.