是否可以使find()和findOne()方法只返回模式字段

Is it possible to make find() and findOne() method return only schema fields

本文关键字:返回 字段 方法 模式 可以使 find 是否 findOne      更新时间:2023-09-26

我在文档中和网上搜索了一个选项,但没有找到任何答案,所以让我们来问这个问题。

为什么要运行以下代码:

var accountSchema = mongoose.Schema({
    id :            { type:Number, unique:true },
    login :         { type:String, unique:true, index:true },
    password :      String,
    usedBySession : String
});
var account = mongoose.model('Account', accountSchema);
account.findOne({id:1}).exec()
    .then(function(result){
        console.log(result);
    },function(err){
        throw err;
    });

我得到所有字段(使用_id),而不是只得到我的模式字段?服务器响应如下。

{"__v":0,"_id":"538deecb900f64d43163759a","id":1,"login":"dbyzero","password":"f71dbe52612345678907ab494817525c6"}

如果没有选项,那么清除响应的最干净的方法是什么?

通过以下方式排除不必要的字段:

account.findOne({id: 1}, '-_id -__v -password') // exclude _id, __v, password fields
    .exec()
    .then(success, failure);

更多信息

或在模式中使用select选项

var yourSchema = new Schema({
   secure: {
       type: String,
       select: false // 'secure' field will not be selected by default
   },
   public: String
});

更多信息