为动态数量的键/值对制作mongoose模式的正确方法

时间:2021-12-25 18:39:33

I have a word counting function that returns an object with a set of key value pairs. Something like this: {a: 4, tale: 3, of: 8, two: 3, cities: 3 }

我有一个单词计数功能,它返回一个带有一组键值对的对象。这样的事情:{a:4,故事:3,of:8,2:3,城市:3}

Obviously this object can be of varying lengths and have different key/value pairs. I'd like to add this data to an 'article' document in Mongodb. Using mongoose.js this is the best schema I can come up with. I'm concerned that mongo is creating a ton of "Word" documents with one key/value pair and an id. Is there a better way?

显然,该对象可以具有不同的长度并且具有不同的键/值对。我想将此数据添加到Mongodb中的“文章”文档中。使用mongoose.js这是我能想到的最好的架构。我担心mongo会创建大量的“Word”文档,其中包含一个键/值对和一个id。有没有更好的办法?

in /models/article.js

在/models/article.js中

mongoose.Schema({
  wordcounts: [wordSchema]
})

in /models/word.js

在/models/word.js中

mongoose.Schema({
  word: String,
  count: Number
})

So the it would end up looking like:

所以它最终看起来像:

[{
_id: 3980923urjf0e232902343252,
wordcounts: [
  {_id: 2039840297502938402934, word: "Apple", count:3}, 
  {_id: 20398sdfsdfsdfaaa4asd3, word: "Banana", count:5}
  ]
}]

Is there a better way?

有没有更好的办法?

1 个解决方案

#1


4  

If you don't need indexing, you can use Schema.Types.Mixed (see: http://mongoosejs.com/docs/schematypes.html )

如果您不需要索引,可以使用Schema.Types.Mixed(请参阅:http://mongoosejs.com/docs/schematypes.html)

Otherwise, you don't have to define a sub-collection, as you could just define it as:

否则,您不必定义子集合,因为您可以将其定义为:

mongoose.Schema({
  wordcounts: [{
    word: String,
    count: Number
  }]
})

#1


4  

If you don't need indexing, you can use Schema.Types.Mixed (see: http://mongoosejs.com/docs/schematypes.html )

如果您不需要索引,可以使用Schema.Types.Mixed(请参阅:http://mongoosejs.com/docs/schematypes.html)

Otherwise, you don't have to define a sub-collection, as you could just define it as:

否则,您不必定义子集合,因为您可以将其定义为:

mongoose.Schema({
  wordcounts: [{
    word: String,
    count: Number
  }]
})