我没用过猫鼬。但这里有一些模式可用于在同步和异步情况下设置默认值。
var DATA={ 56:'somevalue', 77:'Othervalue' };
// SYNC: from JS object
function getPropOrDefault(prop){
var val = DATA[String(prop)];
var ret = (val !== undefined ? DATA[String(prop)] : 'default');
return ret;
};
// ASYNC: from mongoose
function getFromMongoose(key,fn){
//or something. idk how u query mongoose
process.nextTick(function(){
var val = DATA[String(key)];
if(val === undefined) { fn(new Error('no_property')) }
else{ fn(null, val) };
});
};
function getMongoosePropOrDefault(prop, callback){
getFromMongoose(prop, function(err, result){
if(err){
callback(err, 'default');
} else {
callback(null, result);
};
});
};
(function main(){
console.log('DATA[77]: '+getPropOrDefault(77) );
console.log('DATA[99]: '+getPropOrDefault(99) );
getMongoosePropOrDefault(77, function(err, result){
console.log('mongoose.data.77: '+result);
});
getMongoosePropOrDefault(99, function(err, result){
console.log('mongoose.data.99: '+result);
});
})();