If i have a schema in mongoose looking like this (an example):
Meta = new Schema
type_id:Number,
datahash: String,
data: Schema.Types.Mixed
This is all good. I can query Meta.datahash and get the value back etc. But if i query Meta.OtherProp, then i will get an error, as the property does not exisit in the model.
In PHP you have magic methods (getters/setters) that can handle this.
Is there any way to do this in Mongoose (or NodeJS). Examples are very welcome :)
BR/Sune
EDIT: Lets say that data is an object like this:
{
56:'somevalue',
77:'Othervalue'
}
Now - is there any way that i can query directly into this like
Meta.data.56
and then get "somevalue" returned?
And is there again a way to avoid js error of i query
Meta.data.90
as the property does not exist?
I haven't used Mongoose. But here are some patterns that you can use to set defaults in both synchronous and asynchronous cases.
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);
});
})();
Thanks for the replies.
It turns out that if i just set a default value for Meta.data, then i can query non existing properties in the data using the square brackets [] instead of dot notation:
Meta.data[88]
This solves my issue, which was actually related more to js than node or mongoose. Of course this does not work when query sub properties like:
Meta.data[88].something
unless 88 does exist. But again - thats just javascript...