繁体   English   中英

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

[英]Check for not required property existing in mongoose model variable

所以,我有这个猫鼬模式结构:

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");
}

如何正确检查此对象?

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM