2014-11-11 5 views
3

의 배열을 몽구스, 나는이 :설정 기본값은 내 모델 정의에서 노드 JS

appFeatures: [{ 
     name: String, 
     param : [{ 
      name : String, 
      value : String 
     }] 
    }] 

내가 예를 들어, appFeatures에 기본 값을 설정하려면 : 이름 : '기능', PARAM를 : {이름 : 'PARAM1'값 '1'}, {이름 : 'PARAM2'가치 '2'}]

나는,

appFeatures : { type : Array , "default" : ... } 

그러나 그 작업을하지 않음으로써 그것을 시도 어떤 아이디어?

감사합니다.

답변

9

몽구스에서는 스키마 정의를 "분리"할 수 있습니다. 일반적인 "재사용"과 코드 명확성을위한 것입니다. 그래서이 작업을 수행 할 수있는 더 좋은 방법은 다음과 같습니다

// general imports 
var mongoose = require('mongoose'), 
    Schema = mongoose.Schema; 

// schema for params 
var paramSchema = new Schema({ 
    "name": { "type": String, "default": "something" }, 
    "value": { "type": String, "default": "something" } 
}); 

// schema for features 
var featureSchema = new Schema({ 
    "name": { "type": String, "default": "something" } 
    "params": [paramSchema] 
}); 

var appSchema = new Schema({ 
    "appFeatures": [featureSchema] 
}); 

// Export something - or whatever you like 
module.export.App = mongoose.model("App", appSchema); 

그래서 그것은에 시스템을 "필요" "깨끗한", 그리고 "재사용"당신이 "스키마"정의 개별 모듈의 일부를 만들어 사용하고자하는 경우 필요한 경우 가져 오기. 모든 것을 "모듈화"하고 싶지 않으면 "모델"객체의 스키마 정의를 "내성"시킬 수도 있습니다.

대부분의 경우, 기본값으로 "원하는 것을 지정하십시오"를 명확하게 지정할 수 있습니다.

보다 복잡한 기본값을 사용하려면 "미리 저장"훅에서이 작업을 수행하는 것이 좋습니다. 보다 완전한 예를 들어 :

var async = require('async'), 
    mongoose = require('mongoose'), 
    Schema = mongoose.Schema; 

var paramSchema = new Schema({ 
    "name": { "type": String, "default": "something" }, 
    "value": { "type": String, "default": "something" } 
}); 

var featureSchema = new Schema({ 
    "name": { "type": String, "default": "something" }, 
    "params": [paramSchema] 
}); 

var appSchema = new Schema({ 
    "appFeatures": [featureSchema] 
}); 

appSchema.pre("save",function(next) { 
    if (!this.appFeatures || this.appFeatures.length == 0) { 
    this.appFeatures = []; 
    this.appFeatures.push({ 
     "name": "something", 
     "params": [] 
    }) 
    } 

    this.appFeatures.forEach(function(feature) { 
    if (!feature.params || feature.params.length == 0) { 
     feature.params = []; 
     feature.params.push(
     { "name": "a", "value": "A" }, 
     { "name": "b", "value": "B" } 
    ); 
    } 
    }); 
    next(); 
}); 


var App = mongoose.model('App', appSchema); 

mongoose.connect('mongodb://localhost/test'); 


async.series(
    [ 
    function(callback) { 
     App.remove({},function(err,res) { 
     if (err) throw err; 
     callback(err,res); 
     }); 
    }, 
    function(callback) { 
     var app = new App(); 
     app.save(function(err,doc) { 
     if (err) throw err; 
     console.log(
      JSON.stringify(doc, undefined, 4) 
     ); 
     callback() 
     }); 
    }, 
    function(callback) { 
     App.find({},function(err,docs) { 
     if (err) throw err; 
     console.log(
      JSON.stringify(docs, undefined, 4) 
     ); 
     callback(); 
     }); 
    } 
    ], 
    function(err) { 
    if (err) throw err; 
    console.log("done"); 
    mongoose.disconnect(); 
    } 
); 

당신은 그것을 정리하고 다른 수준에서 기본 값을 얻을 수있는 스키마 경로를 성찰 할 수있다. 그러나 기본적으로 내부 배열이 정의되지 않았다면 코드로 기본값을 채울 것이라고 말하고 싶습니다.

+0

감사합니다. 어떻게 featureSchema를 두 개 추가 할 수 있습니까? 내보기처럼? 다시 한 번 감사드립니다! –

+0

@TalLevi 물론입니다. 거기에 두 개의 내부 항목을 추가하는 완전한 예가 추가되었습니다. –