检查猫鼬模型变量中是否存在不需要的属性

时间:2018-09-19 02:30:23

标签: javascript node.js mongoose

所以,我有这种猫鼬结构:

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

正如您在“通知模式”中所看到的,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");
}

如何正确检查此对象?

1 个答案:

答案 0 :(得分:1)

in运算符检查对象自身的属性及其原型链。未设置的属性在对象的原型链中,但不在对象自身的属性中:

  const hasTelegramStatus = 'telegramStatus' in document; // true
  const hasTelegramStatus = document.hasOwnProperty('telegramStatus') // false

一种选择是通过执行document.toObject()将查询转换为对象,这将删除原型链并仅返回自己的属性。

相关问题