scottwrobinson / camo

A class-based ES6 ODM for Mongo-like databases.
557 stars 81 forks source link

When multiple documents with an array of references have ref to the same object, `.loadMany()` adds duplicate references #4

Closed scottwrobinson closed 9 years ago

scottwrobinson commented 9 years ago

This issue happens when there are multiple objects in the database, each object has an array of references, and at least two of the object's arrays contain the same reference.

Consider the following example:

class Eye extends Document {
    constructor() {
        super('eyes');
        this.color = String;
    }
}

class User extends Document {
    constructor() {
        super('users');
        this.eyes = [Eye];
    }
}

var user1 = User.create();
var user2 = User.create();
var eye1 = Eye.create({color: 'blue'});
var eye2 = Eye.create({color: 'brown'});

eye1.save().then(function(e) {
    return eye2.save();
}).then(function(e) {
    user1.eyes.push(eye1, eye2);
    return user1.save();
}).then(function(u) {
    user2.eyes.push(eye1);
    return user2.save();
}).then(function(u) {
    return User.loadMany({});
}).then(function(users) {
    // Get user1
    var u1 = users[0].id === user1.id ? users[0] : users[1];

    // Ensure we have correct number of eyes
    expect(u1.eyes).to.have.length(2);    // FAILS
});

In this case, both user1 and user2 have a reference to eye1. But when we call .loadMany(), both user1 and user2 will have a duplicate reference to eye1, which is not correct.