Javascript 检查mongoose模型变量中是否存在非必需属性
所以,我有一个猫鼬scheemas结构:Javascript 检查mongoose模型变量中是否存在非必需属性,javascript,node.js,mongoose,Javascript,Node.js,Mongoose,所以,我有一个猫鼬scheemas结构: const execStatusScheema = new mongoose.Schema(...) const notifyScheema = new mongoose.Schema({ ... sms: { type: Boolean, required: true }, smsStatus: { type: execStatusScheema }, telegram: { type: Boo
const execStatusScheema = new mongoose.Schema(...)
const notifyScheema = new mongoose.Schema({
...
sms: {
type: Boolean,
required: true
},
smsStatus: {
type: execStatusScheema
},
telegram: {
type: Boolean,
required: true
},
telegramStatus: {
type: execStatusScheema
},
voice: {
type: Boolean,
required: true
},
voiceStatus: {
type: execStatusScheema
}
})
const Notify = mongoose.model('Notify', notifyScheema)
module.exports.Notify = Notify
正如您在Notify scheema smsStatus中所看到的,voiceStatus和telegramStatus不是必需的。如果sms为false,则smsStatus属性在我的代码中不会被分类,对于语音和电报,其行为相同。我想办理入住手续,并通知其中一些酒店。我的做法如下:
const uncomplitedNotifies = await Notify.find(...).select('smsStatus voiceStatus telegramStatus sms voice telegram')
uncomplitedNotifies.forEach(async notify => {
console.log(notify)
if ('telegramStatus' in notify) {
console.log('123')
}
...
结果是:
{ _id: 5ba07aaa1f9dbf732d6cbcdb,
priority: 5,
sms: true,
telegram: false,
voice: false,
smsStatus:
{ status: 'run',
_id: 5ba07aaa1f9dbf732d6cbcdc,
errMessage: 'Authentication failed',
statusDate: '2018-9-18 12:10:19' } }
123
好的,我找到了一个,它是好的,但是我的if语句是真的,即使我的对象中没有这个属性。我猜它签入了scheema对象,在这里声明了它,但我想签入我通过查询得到的“真实”对象。
我也尝试了这个检查案例,但结果相同:
if (typeof something === "undefined") {
alert("something is undefined");
}
如何正确检查此对象?操作员检查对象自身的属性及其原型链。未设置属性位于对象的原型链中,但不在对象自身的属性上:
const hasTelegramStatus = 'telegramStatus' in document; // true
const hasTelegramStatus = document.hasOwnProperty('telegramStatus') // false
一个选项是通过执行
document.toObject()
,将查询转换为对象,这将删除原型链并只返回自己的属性。因此,如果键入if(typeof notify.telegramStatus==“undefined”)console.log('yes')
,您是否可以在控制台中看到yes
,哦,这很有效。我可以看到“是”,所以它没有定义。也许我自己尝试的时候犯了一些错误。