简体   繁体   中英

Using Subclasses in Mongoose Sub Document Array

I have found a couple of solutions for inheritance using Mongoose here and here . These seem to work fine when the documents are stored in a normal collection. But, I am having trouble figuring out how to be able to store an array of the subclassed documents in a sub document on a model.

Let's say we have an object 'drawer' and it contains a collection of 'clothing' objects, where clothing objects can actually be one of several types of clothing 'sock', 'shirt', 'shorts'.

Sock, Shirt, and Shorts are all subclasses of Clothing.

So, I want to have my model Drawer look something like this...

var drawerSchema = mongoose.Schema({
    // some drawer properties here
    // ...
    contents: [clothingSchema]
});

I have tried this approach, but when saved, only the properties of the actual clothingSchema are saved to the DB. For example, if my clothing schema had a common size property, it would be saved, but a property on my shirt object called 'buttonDown' would not be saved.

Has anyone else had a need to do this kind of modeling and if so found a solution?

Thanks!

If you can have inherited Schemas work on independent collections, you can use some Foreign Keys.

var drawerSchema = new Schema({
  contents: [{type: Schema.Types.ObjectId, ref: 'cloth'}],
});

var clothSchema = new Schema({
  size: Number
});

// Then define extended Schemas (Shirt, Sock, Short...)

This approach also lets you have a cloth definition only once in your DB so prevents unnecessary repeat of same data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM