javascript - 在 Mongoose 中返回关联数组而不是文档数组

标签 javascript node.js mongodb mongoose

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

相关文章:

javascript - 从客户端删除任何 session

javascript - 输出未出现在输入字段中,但值存在

javascript - 仅考虑字母和数字在基本字符串中查找句子

javascript - mongoose - 如何让子文档符合模式

c# - 使用 mongodb c# 从字符串数组中提取值(如果包含子字符串)

c# - 在 Azure Functions 中找不到类型或命名空间名称

JavaScript 作业辅导

javascript - 如何使用 Prettier 在代码块之间添加多行?

node.js - Node SOAP 'UNABLE_TO_VERIFY_LEAF_SIGNATURE' 错误

node.js - 最小的 azure node.js 配置以纯文本形式提供 .js 文件,而不是处理它们