I have a document out of Mongo that looks something like this:
{
teacher: { name: 'Fred' },
principal: { name: 'Bob' },
student: { name: 'Sally' }
}
In my case, the properties of "teacher", "principal" and "student" are totally arbitrary and can be any old string. It's unknown before this particular document is loaded what they will be. However, I know that every value of every property at this document level will be of the same type and can therefore validate it.
I would like to make each of these values a sub-document within Mongoose (a "Person") to leverage Mongoose's validation; however, I cannot find a way to tell mongoose to treat all values as the same schema type regardless of key.
By the way, I can't convert this into an array where each Person has "role" type or anything like that. I unfortunately don't control the data structure, I just get to consume it!
Any ideas appreciated!
If you recieve this as a dict, you could implement a converter method that attempts to parse each key value as a Person, something like this:
var utils = require('restberry-utils');
var PersonSchema = new mongoose.Schema({
name: {type: String},
...
});
var Person = mongoose.model('Person', PersonSchema);
var parsePersons = function(persons, next) {
var parsedPersons = {};
var names = Object.keys(persons);
utils.forEachAndDone(names, function(name, iter) {
var personData = persons[name];
Person.findOne(personData, function(err, person) {
if (err) ...
if (!person) {
person = new Person(personData);
}
parsedPersons[name] = person;
person.save(iter);
})
}, function() {
next(parsedPersons);
})
};
var persons = ... // your dict
parsePersons(persons, function(parsedPersons) {
...
});
Does this solve your problem?