假设我有一个具有此架构的 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 中是否有内置的方法来执行此操作?
最佳答案
您不能直接使用 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.
});
关于javascript - 在 Mongoose 中返回关联数组而不是文档数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12229879/