简体   繁体   English

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

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

So, I have this mongoose scheemas structure:所以,我有这个猫鼬模式结构:

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

as you can see in Notify scheema smsStatus, voiceStatus and telegramStatus are not required.正如您在 Notify scheema smsStatus 中看到的那样,不需要 voiceStatus 和 telegramStatus。 If sms is false, the smsStatus property is not assiged in my code, and for voice and telegram the same behavior.如果 sms 为 false,则 smsStatus 属性不会在我的代码中分配,并且对于语音和电报具有相同的行为。 I want to check in Notify some of these propertys.我想检查通知这些属性中的一些。 I do the follow:我执行以下操作:

    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')
    }
...

Result is:结果是:

{ _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

Ok, I find one, and its ok, but my if statment is true even I have no this property in my object.好的,我找到了一个,而且还可以,但是即使我的对象中没有这个属性,我的 if 语句也是正确的。 I guess it check in scheema object, where its declared, but I want to check in my 'real' object I got by query.我猜它会检查其声明的 scheema 对象,但我想检查我通过查询获得的“真实”对象。 I also try this checking case, but the same result:我也尝试过这个检查案例,但结果相同:

if (typeof something === "undefined") {
    alert("something is undefined");
}

How can I check this object correctly ?如何正确检查此对象?

The in operator checks the object's own properties and its prototype chain. in运算符检查对象自己的属性及其原型链。 The unset properties are in the prototype chain of your object, but not on the object's own properties:未设置的属性位于对象的原型链中,但不在对象自身的属性上:

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

One option is to convert the query into an object by doing document.toObject() , which will remove the prototype chain and only return the own properties.一种选择是通过执行document.toObject()将查询转换为对象,这将删除原型链并仅返回自己的属性。

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

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