I have a schema like this (simplified)
var Language = new Schema({
name: String
});
var PartOfSpeech = new Schema({
name: String,
language: { type: ObjectId, ref: "Language" }
});
var Attribute = new Schema({
name: String,
partOfSpeech: { type: ObjectId, ref: "PartOfSpeech" }
});
Is there an easy way to query MongoDB, such that given the _id
of a language, it returns a result set containing all PartOfSpeech
entries referencing that language, and all the Attribute
entries referencing each part of speech?
The result set would look something like this:
[
{
name: "Noun",
attributes: [
{ name: "Plural" },
{ name: "Possessive" }
]
},
{
name: "Verb",
attributes: [
{ name: "Past" },
{ name: "Future" }
]
}
]
Is there a straightforward way to do this in Mongoose?
something like this
PartOfSpeech.find({ language: langId }, function (err, parts) {
if (err) return done(err);
var pending = parts.length;
if (0 === pending) return done(null, parts);
parts.forEach(function (part) {
Attr.find({ partOfSpeech: part }, function (err, attributes) {
if (err) return done(err, parts);
part.attributes = attributes;
if (--pending) return;
done(null, parts)
})
});
})