Why does resolveDBRefs not work with multiple references? #2

nekaab opened this Issue Jun 21, 2011 · 1 comment


None yet

2 participants

nekaab commented Jun 21, 2011

Why is this not possible?

var someSchema = new Schema( {
    id : ObjectId,
    name : String,
    parents : [ {
        type : DBRef,
        resolve : true
    } ]

var someModel = mongoose.model('someCollection', someSchema);

var object1 = new someModel();
object1.name = 'foo';

var object2 = new someModel();
object2.name = 'bar';
object2.parents.push( {
    "$ref" : object1.collection.name,
    "$id" : object1._id

while above code works if I change the Schema to the following:

var someSchema = new Schema( {
    id : ObjectId,
    name : String,
    parents : [ DBRef ]

Did I miss something? Is there a workaround?

Thanks for your help!


This is actually a feature of arrays in mongoose.

Mongoose interprets the value inside the array definition as either a SchemaType or a Schema, both of which are able to be cast values - which is what the MongooseArray.cast function uses. So where you have specified the anonymous object {type: DBRef, resolve: true}, mongoose is attempting to find a cast function on the anonymous object.

What you should really be using is :

var someSchema = new Schema( {
      id : ObjectId,
      name: String,
      parents : { type: [ DBRef ], reslove: true }

However the resolveDBRefs plugin currently only supports resolving DBRef types and not [ DBRef ] types.

If you would like to add the support in that would be great.

Alternatively, you might want to take a look at the mongoose-joins extension that I've pushed to GitHub and npm. This provides some simple (and extensible) join support for 1:n relationships .

Currently only "following" is supported, but I'm going to add push / pull when I get some time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment