简体   繁体   中英

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. If sms is false, the smsStatus property is not assiged in my code, and for voice and telegram the same behavior. 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. I guess it check in scheema object, where its declared, but I want to check in my 'real' object I got by query. 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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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