2015-10-06 186 views
1

我有一個對象,其中有一些對象有時在保存時爲空。我最初的想法是在保存前刪除空的字段,但由於某種原因,似乎沒有工作。對象值保存後仍然存在。貓鼬刪除空對象或陣列

module.exports = function(req, res, next) { 
var newRecipe = new Recipe(req.body); 

newRecipe.pre('save', function (next) { 

    var that = this.data; 

    Object.keys(that.data).forEach(function(key) { 
    if(that.data.hasOwnProperty(key)){ 
     if(typeof that.data[key] != 'undefined'){ 
     if (!that.data[key].length){ 
      delete that.data[key]; 
     }; 
    } 
    } 
}); 

    next(); 
}); 

newRecipe.save(function(err, recipe) { 
    if (err) { 
    console.log(err); 
    res.sendStatus(500); 
    } else { 
    res.sendStatus(200); 
    } 
}); 
}; 

這裏是我的傳入對象:

{ 
    notes: [], 
    isHostessGift: false, 
    playbook: {}, 
    location: {}, 
    wine: { ingredient: false, pairing: false }, 
    coupons: [], 
    ingredients: [{ item: 'd' }], 
    categories: { dishType: ["Beverage"], mainIngredient: ["d"] }, 
    directions: [{ step: 'd' }], 
    serves: 9, 
    cookTime: 9, 
    prepTime: 8, 
    headline: 'ccc' 
} 

是否有這更好的方法呢?

編輯:由於某些原因,從chridam的回答中工作繼承的屬性正在通過hasOwn屬性函數。

var hasOwnProperty = Object.prototype.hasOwnProperty; 

function isPropertyEmpty(obj) { 
if (obj == null)  return true; 
if (obj.length > 0) return false; 
if (obj.length === 0) return true; 
for (var key in obj) { 
    if (hasOwnProperty.call(obj, key)){ 
     console.log(key); 
    } 
} 
return true; 


} 



module.exports = function(req, res, next) { 
    var newRecipe = new Recipe(req.body); 

newRecipe.pre('save', function (next) { 

var doc = this; 
    Object.keys(doc).forEach(function(key) { 
     if (isPropertyEmpty(doc[key])){ 
      // console.log(_.omit(doc, doc[key])); 
     }; 
    }); 

console.log(doc); 


    next(); 
}); 

慰問了DOC:

strictMode 
selected 
shardval 
saveError 
validationError 
adhocPaths 
removing 
inserting 
version 
getters 
_id 
populate 
populated 
wasPopulated 
scope 
activePaths 
ownerDocument 
fullPath 
emitter 
createdAt 
sites 
published 
featured 
data 
_id 
slug 
image 
$__original_save 
save 
$__original_save 
save 
{ image: 'lol.jpg', 
    slug: 'lol', 
    _id: 561522878ff1d2f9ae9b4323, 
    data: 
    { headline: 'lol', 
    prepTime: 22, 
    cookTime: 6, 
    serves: 8, 
    directions: [ [Object] ], 
    categories: { mainIngredient: [Object], dishType: [Object] }, 
    ingredients: [ [Object] ], 
    coupons: [], 
    wine: { pairing: false, ingredient: false }, 
    location: {}, 
    playbook: {}, 
    isHostessGift: false, 
    notes: [] }, 
    featured: false, 
    published: false, 
    sites: [ 'HOL' ], 
    createdAt: Wed Oct 07 2015 09:47:51 GMT-0400 (EDT) } 
+0

你能顯示你的模式嗎? –

+0

您可以刪除數據對象的屬性,但架構是具體的。所有未定義的屬性都將通過貓鼬使用默認值(空值,空值,'')值進行保存。 –

回答

2

我有一個很大的問題,這個解決方案時有嵌套可選Array場模式。我解決了這個創建一個新的類型:

optional_array = 
    type: Mixed 
    validate: 
    validator: (v) -> 
     return v instanceof Array 
    message: '{VALUE} needs to be an array.' 

,然後我的所有字段設置爲optional_array而不是Array