Mongoose: save nested JSON with various schemas

everything. I want to save JSON documents with many levels, for example, I have nested JSON with these elements:

{   
 "created":"2015-11-10 15:47:41.107Z",
 "id_user" : "01",
 "version" : "1"
 "record" : {
    "name" : "Carl Powers",
    "reference" : [{ "url" : "www.test.com", "created" : "2015-11-10 15:47:41.107Z"}] 
 }
}

I want to save this JSON using different schemes for each element, because I need different collections in my MongoDB, I don't want a scheme with inline elements.

var ElementSchema = new Schema({
 created : {type: Date, default: Date.now},
 id_user : String,
 version : { type: Number, min: 0 },
 record : {type: Schema.Types.ObjectId, ref: 'recordSchema'}
});

var recordSchema = new Schema({
    name : String,
    reference : [{type: Schema.Types.ObjectId, ref: 'referenceSchema'}]
});

var referenceSchema = new Schema({
    url : String,
    created : {type: Date, default: Date.now}
  });

You can save my JSON example, completely, at a time, using mongoose. Do I need to enter the identifiers of each element? In this case, what is the best way to create each identifier and how to put in each element after receiving JSON?

+4
source share
1 answer

This can be solved using subdocuments, here is an example:

var referenceSchema = new Schema({
    url : String,
    created : {type: Date, default: Date.now}
});

var recordSchema = new Schema({
    name : String,
    reference : [referenceSchema]
});

var ElementSchema = new Schema({
 created : {type: Date, default: Date.now},
 id_user : String,
 version : { type: Number, min: 0 },
 record : recordSchema
});

Element :

var element = new ElementSchema({
   created: 'date',
   id_user: 'user-id',
   version: 2
   record: {
      name: 'name',
      reference: [{
         url: 'url1',
         created: 'date1'
      }, {
         url: 'url2',
         created: 'date2'
      }]
   }
});

:

0

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


All Articles