Skip to content

Commit

Permalink
fix: handle autopopulate within nested document array when top-level …
Browse files Browse the repository at this point in the history
…array is empty

Fix #70
  • Loading branch information
vkarpov15 committed Mar 29, 2020
1 parent 759b6a3 commit 3e544fc
Show file tree
Hide file tree
Showing 3 changed files with 48 additions and 4 deletions.
5 changes: 3 additions & 2 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,9 @@ module.exports = function(schema) {
}
autopopulateHandler.call(this, options => {
const pop = this.populated(options.path);
if (pop != null) {
return Array.isArray(pop) && pop.length !== this.get(options.path).length;
if (Array.isArray(pop)) {
const docVal = this.get(options.path);
return docVal == null || pop.length !== docVal.length;
}
return true;
});
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
"co": "4.6.0",
"co-mocha": "1.2.2",
"mocha": "5.1.1",
"mongoose": "~5.3",
"mongoose": "5.x",
"nyc": "11.7.3"
},
"peerDependencies": {
Expand Down
45 changes: 44 additions & 1 deletion test/bugs.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,26 @@ describe('bug fixes', function() {
let db;

before(function() {
db = mongoose.createConnection('mongodb://localhost:27017/autopopulate');
db = mongoose.createConnection('mongodb://localhost:27017/autopopulate', {
useUnifiedTopology: true,
useNewUrlParser: true
});
});

after(function(done) {
db.close(done);
});

beforeEach(function() {
const promises = [];
for (const modelName of Object.keys(db.models)) {
const Model = db.model(modelName);
promises.push(Model.deleteMany({}));
}

return Promise.all(promises);
});

it('gh-15', function(done) {
const opts = {
timestamps: { createdAt: 'createdAt' },
Expand Down Expand Up @@ -202,4 +215,34 @@ describe('bug fixes', function() {
assert.equal(docs[0].items[0].name, 'test');
});
});

it('handles autopopulate in nested doc array when top-level array is empty (gh-70)', function() {
const User = db.model('User', Schema({ name: String }));
db.model('Card', Schema({ name: String }));
const GameSchema = new Schema({
players: [{
type: 'ObjectId',
ref: 'User',
autopopulate: true
}],
state: [{
cards: [{
card: { type: 'ObjectId', ref: 'Card', autopopulate: true }
}]
}]
});
GameSchema.plugin(autopopulate);
const Game = db.model('Game', GameSchema);

return co(function*() {
const player = yield User.create({ name: 'test' });
yield Game.create({ players: [], state: [] });

const doc = yield Game.findOne();
doc.players.push(player._id);
yield doc.save();

assert.deepEqual(doc.toObject().state, []);
});
});
});

0 comments on commit 3e544fc

Please sign in to comment.