2012-01-30 21 views
10

से संपत्ति को निकालना मैं कुछ डेटा स्टोर करने के लिए नोड.जेएस और मोंगोस का उपयोग कर रहा हूं। अद्यतन के बाद, मेरे पास निम्न संरचना है:मोंगोस, मॉडल

{ created: Mon, 30 Jan 2012 19:25:57 GMT, 
    _id: 4f21a6028132fba40f0000b7, 
    features: 
    { imdb_id: 'tt0822975', 
    released: '2007-03-24', 
    tvdb_id: 103191, 
    type: 'series', 
    names: [ 'DinoSapien' ], 
    pictures: [], 
    cast: [], 
    genres: [ 'Action and Adventure', 'Children' ] }, 
    type: 1 } 

मुझे उदा। इस दस्तावेज़ पर cast और pictures फ़ील्ड। हालांकि, मैं डेटाबेस से खाली सरणियों दूर करने के लिए एक समाधान आवेदन किया है, लेकिन यह काम नहीं करता है:

instance = (an instance from calling findOne on my model) 
cast = (an array) 
if (cast && cast.length > 0){       
    instance.features.cast = cast;      
} else { 
    delete instance.features.cast; 
} 
console.log(cast); // null 
console.log(instance), // cast is not removed! 

क्या यह संभव है मॉडल से खाली सरणियों या अवांछित मूल्यों को दूर करने के लिए जब डाटाबेस के लिए बचत?

उत्तर

9

आप उन खाली क्षेत्रों के लिए जाँच करने के लिए एक पूर्व बचाने के हुक का उपयोग कर सकते हैं, और उन्हें undefined इस तरह करने के लिए सेट:

PostSchema.pre('save', function (next) { 
    if(this.pictures.length == 0){ 
     this.pictures = undefined; 
    } 
    if(this.cast.length == 0){ 
     this.cast = undefined; 
    } 

    next(); 
}); 

मैं इस स्थानीय रूप से परीक्षण किया है और यह काम ठीक करने के लिए लगता है।

+0

ऐसा लगता है कि आप ऑब्जेक्ट आईडी प्रकार फ़ील्ड के साथ ऐसा नहीं कर सकते हैं, लेकिन सोचने का अच्छा तरीका! :) – panosru

संबंधित मुद्दे