我在文档和网上搜索了一个选项,但没有找到任何答案,所以让我们提出这个问题。
为什么要运行以下代码:
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);
或使用架构中的选择
选项
var yourSchema = new Schema({
secure: {
type: String,
select: false // 'secure' field will not be selected by default
},
public: String
});
关于javascript - 是否可以使 find() 和 findOne() 方法仅返回架构字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28410514/