brunouno
brunouno

Reputation: 595

mongoose-schema - are both children array + parent doc's ID necessary?

I'm using a couple of one-to-many models and was wondering what the advantage of having both an array of "children" ObjectID()s and a "parent" model's ObjectID() in the child is. For example:

// a client will have a new card every ten visits
var ClientSchema = new Schema({
    first_name: String,
    last_name: String,
    email: String,
    cards: [] // ObjectID()s, <--- is this necessary?
});

var CardSchema = new Schema({
    client: ObjectID(), // <--- or is this enough?
    visits: []
});

I think the client: ObjectID() should do the trick in most cases, specially with the Population options Mongoose offers.

Upvotes: 0

Views: 1201

Answers (1)

Pim van der Heijden
Pim van der Heijden

Reputation: 7970

It suffices to store the reference ObjectId in one of the documents.

As you can read in the documentation or in this answer, the reference field needs a type and a ref. The name of field is arbitrary. Once you have done this and registered your models, you can use the models to populate your queries.

var clientSchema = new Schema({
    first_name: String,
    last_name: String,
    email: String
});

var cardSchema = new Schema({
    client: {
        type: Schema.Types.ObjectId,
        ref: 'client'
    }
});

// models
var Card = mongoose.model('Card', cardSchema);
var Client = mongoose.model('Client', clientSchema);

Yet, it could be helpful to store an array of ObjectId's. However, this also creates a huge window for mistakes. A mismatch of foreign key and primary key, in SQL dialect. You can always do a count query if you need to count. I would say, do either the above or do this:

var clientSchema = new Schema({
    first_name: String,
    last_name: String,
    email: String,
    cards: [
        {
            type: Schema.Types.ObjectId,
            ref: 'card'
        }
    ]
});

var cardSchema = new Schema({
    card_name: String
});

// models
var Card = mongoose.model('Card', cardSchema);
var Client = mongoose.model('Client', clientSchema);

Upvotes: 1

Related Questions