Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/node.js/41.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在mongoose中返回关联数组而不是文档数组_Javascript_Node.js_Mongodb_Mongoose - Fatal编程技术网

Javascript 在mongoose中返回关联数组而不是文档数组

Javascript 在mongoose中返回关联数组而不是文档数组,javascript,node.js,mongodb,mongoose,Javascript,Node.js,Mongodb,Mongoose,假设我有一个具有此模式的单词模型 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

假设我有一个具有此模式的单词模型

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来实现这一点,但是如果您可以查看查询结果,则可以非常轻松地构建所需的关联数组:

Word.find().lean().exec(function (err, docs) {
    // docs are plain javascript objects instead of model instances
});
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.
});

您可以使用reduce函数将任何数组“重新索引”到字典中。在我的示例中,我使用下划线reduce,但我认为只要稍加调整,它就可以直接在mongoose中工作


但是它仍然返回一个数组,而不是键值对象。这似乎只是返回一个以文档为值的单键,而不是实际的单词条目(将是普通对象,而不是键/值对)。流只需调用('data'),调用整个文档即可。
_.reduce (foo, function (reduced, item) {
 reduced[item.name] = item;
 return reduced;
}, {});