Why does resolveDBRefs not work with multiple references? #2

Closed
nekaab opened this Issue Jun 21, 2011 · 1 comment

Projects

None yet

2 participants

@nekaab
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';
object1.save();

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

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!

@goulash1971
Owner

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