使用Mongoose使用非ObjectId字段引用集合的策略

时间:2013-08-04 13:01:23

标签: node.js database-design mongoose

拥有一系列项目和一系列类别我希望将它们联系起来考虑到所有查询都将针对项目集合进行,类别总是包含很少的文档。 我不想依赖于类别的数字或自动生成的mongodb哈希id,因为以这种方式设置每个项目中的类别更灵活,更易于阅读:myItem.category ='CATEGORY_CODE'。这允许任何客户端只使用可以在本地存储的类别代码,并且可以预测与本机mongodb id相反。

以下是模型:

//Item.js

var ItemSchema = new Schema({
  name: { type: String, default: 'default_name', trim: true },
  category: { type: Schema.Types.ObjectId, ref: 'Category' },

});

mongoose.model('Item', UserSchema)


//Category.js

// Note: 'uncat' is the category code for 'uncategorized'
var CategorySchema = new Schema({
  _id: { type: String, default: 'uncat', lowercase: true, trim: true },
  translation: [ { lang_code: String, text: String}]


});
mongoose.model('Category', CategorySchema);

所以问题是:

是否可以(并推荐)禁用CategorySchema中的“_id”字段并使用另一个字段(即“代码”)并引用Item.Category中的CategorySchema.code? 你知道另一种可以与这种情况相匹配的策略吗?

类别模式会像这样:

var CategorySchema = new Schema({
  code: { type: String, default: 'uncat', lowercase: true, trim: true },
  translation: [ { lang_code: String, text: String}]
}
_id: false
);

1 个答案:

答案 0 :(得分:0)

我现在正面临类似的问题。

据我所知,你无法“禁用”_id字段。您可以做的是将其定义为其他内容,就像您在CategorySchema上所做的那样。

在ItemSchema上,您应该将类​​别更改为:

category: { type: String, ref: 'Category' }

由于CategorySchema上的_id是String,而不是ObjectId。

但是,目前这对我不起作用(至少不像我预期的那样)。当我这样做时,我被允许插入集合中不存在的值并保存模型而不会出错。因此,在模型保存中不会验证引用。