假设我有一个带有此架构的Word模型
var Word = new Schema({
name: { type: String, required: true },
disambiguation: String,
partOfSpeech: { type: ObjectId, ref: "PartOfSpeech", required: true },
attributes: [{ type: ObjectId, ref: "Attribute"}],
root: [{ type: ObjectId, ref: "Word"}],
language: { type: ObjectId, ref: "Language", required: true }
});
我想执行一个返回对象的查询,其中单词名称为键,值为包含具有相应名称的单词的文档数组。
作为一个例子,这是我想要的那种输出。为简洁起见,大多数字段都被省略了。
{
stick: [{
_id: "5024216f6df57b2b68834079",
partOfSpeech: "noun"
}, {
_id: "678451de6da54c2b68837345",
partOfSpeech: "verb"
}],
dog: [{
_id: "47cc67093475061e3d95369d",
partOfSpeech: "noun"
}]
}
这样,我可以随机访问单词列表,所以我不必重复迭代它。是否有内置的方法在mongoose中执行此操作?
答案 0 :(得分:2)
Word.find().lean().exec(function (err, docs) {
// docs are plain javascript objects instead of model instances
});
答案 1 :(得分:2)
您无法直接使用Mongoose执行此操作,但如果您stream查询结果,则可以非常轻松地构建所需的关联数组:
var stream = Word.find().stream(), results = {};
stream.on('data', function(doc) {
if (results.hasOwnProperty(doc.name)) {
results[doc.name].push(doc);
} else {
results[doc.name] = [doc];
}
}).on('error', function(doc) {
// Error handling...
}).on('close', function(doc) {
// All done, results object is ready.
});
答案 2 :(得分:1)
您可以使用reduce函数将任何数组“重新索引”到字典中。我在我的例子中使用了下划线缩减,但我想稍微调整它可以直接在mongoose中工作。 http://techishard.wordpress.com/2012/04/22/reducing-an-array-of-objects-to-a-hash-using-a-property-as-key/
_.reduce (foo, function (reduced, item) {
reduced[item.name] = item;
return reduced;
}, {});