Search code examples
node.jsmongodbmongoosemongoose-schema

With Mongoose, what is the proper way to initalize a new object instance that already contains embedded data?


Let's say that I have some data that I'm getting back from an API that I want to save. All together, there are 4 models that are referenced inside each other, A > B > C > D, and the schemas are defined as so:

// Schemas

const A = new Schema({
  username: String,
  password: String,
  B: [B.schema],
});

const B = new Schema({
  name: String,
  C: C.schema,
});

const C = new Schema({
  a: [D.schema],
  b: [D.schema],
  c: [D.schema],
});


const D = new Schema({
  name: String,
});

I initialize A and B separately, as A is created for my app only, while I save an instance of B to A after calling an external API. However, when I initialize B, I would already have all of the data from C and D that I would need (assuming there are no errors when getting the data).

So when initializing an instance of B, would the already embedded instances of C and D be initialized as instances of my C and D model automatically, since they would fit the way I defined the schemas? Or would I have to use nested for loops to initialize each item individually?

For example:

const apiResponse = {
 name: 'example',
 C: {
  a: [D, D, D],
  b: [D, D, D],
  c: [D, D, D]
 } 
}

// To initialize, do I option 1:
const newB = new db.B(apiResponse)

// Or do I do something like option 2:
const C = {};
for (key in apiResponse.C) {
 apiResponse.C[key].forEach(item => C[key].push(new db.D(item)));
}
const newC = new db.C(C);
const newB = new db.B({ name: apiResponse.name, C: newC })

Solution

  • So I opted for option 1 as described above (const newB = new db.B(apiResponse)), and it seems to initialize everything in the object that fits the embedded schemas automatically.