mongoose schema 如下
const userSchema = new Schema({
username: String,
password: String,
age: Number,
isLogin: Boolean,
});
我们插入一条记录
const user = new User({
username: 'pandora',
password: 'pandora', // 真实情况下密码不会存储明文
})
await user.save();
当我们正常判断一个属性是否存在时
if (user.age) {
// doSomething
}
这是没有问题的。
当我们判断一个布尔类型的属性时,一般会采用这种方式
console.log('isLogin' in user); // true
由于我们定义了schema约束,所以所以定义在schema上的属性都会设置在document上,即使没有指定默认值,所以我们应该采用以下这种方式
console.log(typeof user.isLogin === 'boolean'); // false