Mongoose互相嵌入文件

时间:2015-05-07 01:07:25

标签: node.js mongodb mongoose denormalization

我有一个包含这些集合的mongoDb数据库

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:
}

如你所见,我对字段进行了非规范化。现在我无法弄清楚如何将它与mongoose模式联系起来。

我有这个,但这似乎不对:

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]
});

我的非规范化是错误的吗?(应用程序需要获取categoryname& productname很多,这就是为什么我反规范化了)

1 个答案:

答案 0 :(得分:1)

你的猫鼬语法有点偏。试试这个(下面):

请注意,我已建议删除根架构的_id字段。 Mongo将自动生成_id字段,类型为ObjectId,可以派上用场。如果您愿意,可以使用_id: Number来覆盖此选项,但如果您有充分的理由,我建议您这样做。

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
    }]
});