【问题标题】:Return an associative array instead of a document array in mongoose返回关联数组而不是 mongoose 中的文档数组
【发布时间】:2012-10-25 11:43:06
【问题描述】:

假设我有一个具有此架构的 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"
  }]
}

这样,我可以随机访问单词列表,因此我不必反复迭代它。猫鼬有内置的方法吗?

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    您不能直接使用 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.
    });
    

    【讨论】:

    • 这似乎只会返回一个以文档为值的键,而不是实际的单词条目(这将是普通对象,而不是键/值对)。流只需调用on('data') 即可获取整个文档。
    【解决方案2】:
    Word.find().lean().exec(function (err, docs) {
        // docs are plain javascript objects instead of model instances
    });
    

    【讨论】:

    • 但是它仍然返回一个数组而不是一个键值对象
    【解决方案3】:

    您可以使用 reduce 函数将任何数组“重新索引”到字典中。我在我的示例中使用了下划线 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;
    }, {});
    

    【讨论】:

      猜你喜欢
      • 2019-02-19
      • 2017-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-20
      • 1970-01-01
      • 2021-08-20
      • 2015-04-18
      相关资源
      最近更新 更多