DbRef with Mongoose - mongoose-dbref or populate?

2019-01-25 23:13发布

问题:

I have the following 2 schemas:

Company Event:

var companyEventSchema = new Schema({
    name : String,
    description
    date : Date,
    attendees : [ { type : Schema.ObjectId, ref : 'Member' } ],
]});

And Member

var memberSchema = new Schema({
    name : String,
    emailAddress: String,
    password :String,
    created: { type: Date, default: Date.now }
});

Is the way i've ref'd Member from companyEventSchema correct? I'm trying to do something a long the lines of a dbref.

I saw theres a separate project for that though... mongoose-dbref

However, the mongoose docs say the above provides "dbref like functionality"

Which would be more efficient?

回答1:

You only need to use an actual DBRef (and mongoose-dbref) for the case where a field can contain ObjectIds that reference documents in potentially more than one collection. A DBRef is a tuple of an ObjectId, a collection name, and an optional database name.

Mongoose ref: fields, however, contain just an ObjectId and it's the Mongoose schema that defines what one collection the ObjectIds reference.

So Mongoose ref: fields are more efficient and should always be used unless you need the multi-collection reference support that DBRef provides.