Endymion
Endymion

Reputation: 782

Strategies for referencing collections using non ObjectId fields using Mongoose

Having a collection of items and a collection of categories I want to relate them having into account that all queries will be done against item collection and categories always will contain very few documents. I don't want to rely on a numeric or autogenerated mongodb hash id for categories because it is more flexible and human-readable to set the category in each item in this way: myItem.category ='CATEGORY_CODE'. This allows any client to work only with category codes which can be stored locally and are predictable as opposite to native mongodb ids.

Here are the models:

//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);

So questions are:

Is it possible (and recommended) to disable the "_id" field in CategorySchema and use another field (i.e 'code') and reference CategorySchema.code from Item.Category? Do you know another strategy that could match this scenario?

Category schema would be somethig like this:

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

Upvotes: 0

Views: 186

Answers (1)

Alejandro Nagy
Alejandro Nagy

Reputation: 738

I'm facing a similar issue myself right now.

As far as I know, you can't "disable" the _id field. What you can do is define it as something else, as you did on your CategorySchema.

On ItemSchema you should change your category to:

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

Since the _id on the CategorySchema is String, not ObjectId.

However, this is not working for me currently (at least not as I expected). When I do this I'm allowed to insert values that do not exist on the collection and save the Model without errors. So the reference is not validated on Model save.

Upvotes: 1

Related Questions