Mongoose: saving as an associative array of subdocuments and an array of subdocuments

I have a set of documents for which I must maintain consistency. Due to the way MongoDB handles operations with multiple documents, I need to embed this set of documents in a container document to ensure the atomicity of my operations.

Data attaches great importance to the keyboard shortcut. Is there a way instead:

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

Can I instead have subdocs be an associative array (i.e. an object) that applies sub-checks to? Thus, the container instance will look something like this:

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

thanks

+4
source share
2 answers

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

Take a look at the structure you are proposing:

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

Since you must predefine the schema in Mongoose, you must know your key names in advance. In this case, we probably would not know in advance what dates we are collecting data, so this is not a good option.

If you are not using Mongoose, you can do it without any problems. MongoDB itself is highlighted when 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" } 

In this case, adding Mongoose on top of MongoDB takes away some of MongoDBโ€™s own flexibility. If your use case fits well with this MongoDB feature, then using Mongoose might not be the best choice.

+4
source

you can achieve this using { strict : false} in your mongoose pattern, although you should check the consequences of the check and the mongoose casting mechanism.

 var flexibleSchema = new Schema( {},{strict: false}) 

another way uses the schema.add method , but I don't think this is the right solution.

the last solution that I see is to get the entire array on the client side and use underscore.js or any library you have. but it depends on your application, document size, communication steps, etc.

+2
source

Source: https://habr.com/ru/post/1502456/


All Articles