是否可以使 find() 和 findOne() 方法 return 只有模式字段
Is it possible to make find() and findOne() method return only schema fields
我在文档中和网上搜索了一个选项,但没有找到任何答案,所以让我们提出这个问题。
为什么用运行下面的代码:
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
});
我在文档中和网上搜索了一个选项,但没有找到任何答案,所以让我们提出这个问题。
为什么用运行下面的代码:
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
});