Nick
Nick

Reputation: 575

Mongoose embedded documents of each other

I have a mongoDb database with these collections

collection: Category
{
 id:
 catnumber:
 nameNL:
 nameFR:
 subcategories:[id:, nameNL:, nameFR]
 products:[id,nameNL,nameFR]
}
Collection: Product
{
 id:
 nameNL:
 nameFR:
 descriptionNL:
 descriptionFR:
 code1:
 code2:
 categories:[id:,nameNl:,nameFR]
 image:
}

as you see I denormalized the fields.Now i can't figure out how to link this with mongoose schema.

I have this, but this doesn't seems to be right:

var Schema = mongoose.Schema;
var ProductSchema = new Schema({
 _id: Number,
 nameNL: String,
 nameFR:String,
 descriptionNL:String,
 descriptionFR:String,
 code1:String,
 code2:String,   
 categories: [CategorySchema._id,CategorySchema.nameNL,CategorySchema.nameFR]
});

var CategorySchema = new Schema({
 _id:Number,
 catNumber: String,
 nameNL: String,
 nameFR:String,
 subcategories:[CategorySchema.nameNL,CategorySchema.nameFR],
 products:[ProductSchema._id,ProductSchema.nameNL,ProductSchema.nameFR]
});

Is my denormalization wrong?(The application need to fetch categoryname & productname a lot thats why i denormalized it)

Upvotes: 1

Views: 262

Answers (1)

Andrew Lavers
Andrew Lavers

Reputation: 8141

Your mongoose syntax is a bit off. Try this (below):

Note that I've suggested removing the _id fields of your root schemas. Mongo will generate an _id field for you automatically, of type ObjectId, which can come in handy. You do have the option of overriding this if you wish, with _id: Number but I would only recommend doing that if you have a good reason for it.

var Schema = mongoose.Schema;
var ProductSchema = new Schema({
    nameNL: String,
    nameFR: String,
    descriptionNL: String,
    descriptionFR: String,
    code1: String,
    code2: String,
    categories: [{
        _id: { type: Schema.Types.ObjectId, ref: 'Category' },
        nameNL: String,
        nameFR: String
    }]
});

var CategorySchema = new Schema({
    catNumber: String,
    nameNL: String,
    nameFR: String,
    subcategories: [{
        _id: { type: Schema.Types.ObjectId, ref: 'Category' },
        nameNL: String,
        nameFR: String   
    }],
    products: [{
        _id: { type: Schema.Types.ObjectId, ref: 'Product' },
        nameNL: String,
        nameFR: String
    }]
});

Upvotes: 1

Related Questions