我有以下架构。
var UserSchema = new mongoose.Schema({
username: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
test: {
type: String,
default: 'hello world'
}
});
UserSchema.pre('save', function(callback) {
var user = this;
this.test = undefined; // here unset test field which prevent to add in db
});
module.exports = mongoose.model('User', UserSchema);
但是当我找到数据时
User.find(function(err, users) {
if (err)
res.send(err);
res.json(users);
});
它总是返回
[
{
_id: "56fa6c15a9383e7c0f2e4477",
username: "abca",
password: "$2a$05$GkssfHjoZnX8na/QMe79LOwutun1bv2o76gTQsIThnjOTW.sobD/2",
__v: 0,
test: "hello world"
}
]
如果没有test
字段并且查询没有任何变化,我如何修改或添加任何特殊参数来获取数据
User.find({}, '-test', function (err, users){
});
此外,我在模型中设置了默认值:test: "hello world"
但我不希望这个值出现在响应中。
我还设置了 this.test = undefined;
这应该意味着它阻止将此默认值添加到数据库中,但是我仍然收到此响应。
最佳答案
将您的架构设置为
test: {
type: String,
default: 'hello world',
select: false
}
关于node.js - 如何限制在 find() 期间数据库中不存在的 Mongoose 默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36284077/