猫鼬只选择在模式中明确声明的字段

猫鼬只选择在模式中明确声明的字段

问题描述:

在使用Mongoose并查询数据库时,默认情况下会选中所有字段,并且我必须明确告诉Mongoose我不想选择哪些字段,例如,如果我不想使用user字段,我应该这样做:

When using Mongoose and querying the DB, by default all fields are selected, and I have to explicitly tell Mongoose which fields I do not want to select, for instance if I do not want the field user I should do:

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

问题是,可能在API开发人员(me)不了解的情况下将字段添加到db中.

The problem is, fields might be added to the db without the API developer (me) knowing about it.

是否可以告诉猫鼬选择明确设置的字段?

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

有一种变通方法是始终仅选择在Schema中定义的字段.您要做的就是获取具有模式paths属性的所有字段,并将其传递给您的select()语句,例如:

There's a workaround to always select only fields defined in your Schema. What you have to do is to get all fields with the schema paths property and pass it to your select() statement, like:

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

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

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

That way, even if someone add a new field to your objects, it'll never be shown. The disadvantage is that you have to do that for every query.