0

Is there a way to restrict which fields are sent in the response at a model level. Assume I have the following schema:

var mySchema = new.mongoose.Schema({
    public_field1: String,
    public_field2: String,
    private_field1: String,
    private_field1: String,
})

Let's say I want to get all those fields back when I do my query because the private fields are used for some processing, but I only want to send the public fields to the final response. What is the best way to handle that without having to specify it every single route function?

4

1 回答 1

0

您可以使用select架构中字段定义的属性来确定默认情况下是否包含该字段。例如,要默认排除私有字段:

var mySchema = new.mongoose.Schema({
    public_field1: String,
    public_field2: String,
    private_field1: {type: String, select: false},
    private_field2: {type: String, select: false}
})

然后,当您确实需要这些字段时,您可以通过以下方式将它们包含在结果中:

MyModel.find().select('+private_field1 +private_field2').exec(callback);
于 2013-11-06T00:22:14.443 回答