猫鼬:另存为子文档和子文档的关联数组 [英] Mongoose: Saving as associative array of subdocuments vs array of subdocuments

查看:67
本文介绍了猫鼬:另存为子文档和子文档的关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要保持持久性的一组文档.由于MongoDB处理多文档操作的方式,我需要将这组文档嵌入容器文档中,以确保操作的原子性.

I have a set of documents I need to maintain persistence for. Due to the way MongoDB handle's multi-document operations, I need to embed this set of documents inside a container document in order to ensure atomicity of my operations.

数据非常适合键值配对.有什么办法可以代替:

The data lends itself heavily to key-value pairing. Is there any way instead of doing this:

var container = new mongoose.Schema({
   // meta information here
   subdocs: [{key: String, value: String}]
})

我可以让subdocs是应用子文档验证的关联数组(即对象)吗?因此,容器实例看起来像:

I can instead have subdocs be an associative array (i.e. an object) that applies the subdoc validations? So a container instance would look something like:

{
   // meta information
   subdocs: {
       <key1>: <value1>,
       <key2>: <value2>,
       ...
       <keyN>: <valueN>,
   }
}

谢谢

推荐答案

使用猫鼬,我不认为有一种方法可以完成您所描述的事情.为说明起见,让我们举一个例子,其中您的键是日期,而值是高温,以形成类似{"2012-05-31":88}的对.

Using Mongoose, I don't believe that there is a way to do what you are describing. To explain, let's take an example where your keys are dates and the values are high temperatures, to form pairs like { "2012-05-31" : 88 }.

让我们看看您提出的结构:

Let's look at the structure you're proposing:

{
   // meta information
   subdocs: {
       "2012-05-30" : 80,
       "2012-05-31" : 88,
       ...
       "2012-06-15": 94,
   }
}

由于必须在Mongoose中预定义架构,因此必须提前知道键名.在此用例中,我们可能不会提前知道要收集数据的日期,因此这不是一个好选择.

Because you must pre-define schema in Mongoose, you must know your key names ahead of time. In this use case, we would probably not know ahead of time which dates we would collect data for, so this is not a good option.

如果您不使用猫鼬,则可以毫无问题地做到这一点. MongoDB本身擅长在现有文档中插入具有新键名的值:

If you don't use Mongoose, you can do this without any problem at all. MongoDB by itself excels at inserting values with new key names into an existing document:

> db.coll.insert({ type : "temperatures", subdocuments : {} })
> db.coll.update( { type : "temperatures" }, { $set : { 'subdocuments.2012-05-30' : 80 } } )
> db.coll.update( { type : "temperatures" }, { $set : { 'subdocuments.2012-05-31' : 88 } } )
{
    "_id" : ObjectId("5238c3ca8686cd9f0acda0cd"),
    "subdocuments" : {
        "2012-05-30" : 80,
        "2012-05-31" : 88
    },
    "type" : "temperatures"
}

在这种情况下,在MongoDB之上添加Mongoose会失去MongoDB的一些本机灵活性.如果您的用例非常适合MongoDB的此功能,那么使用Mongoose可能不是最佳选择.

In this case, adding Mongoose on top of MongoDB takes away some of MongoDB's native flexibility. If your use case is well suited by this feature of MongoDB, then using Mongoose might not be the best choice.

这篇关于猫鼬:另存为子文档和子文档的关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆