[英]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.