Skip to content
This repository has been archived by the owner on Feb 10, 2022. It is now read-only.

Commit

Permalink
fix collection name detection
Browse files Browse the repository at this point in the history
  • Loading branch information
Vadim Demedes committed Jun 26, 2017
1 parent 7a6ea85 commit 4977e45
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
10 changes: 5 additions & 5 deletions lib/model.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ function Model(fields) {
this.set(initialFields);
}

Model.prototype.collection = function () {
return pluralize(this.constructor.displayName || this.constructor.name).toLowerCase();
};

Model.prototype.getConnection = function () {
return this.constructor.getConnection();
};
Expand Down Expand Up @@ -117,10 +121,6 @@ Model.prototype.increment = function (key, value = 1) {
return this.store.dispatch(increment(fields));
};

Model.collection = function () {
return pluralize(this.displayName || this.name).toLowerCase();
};

Model.getConnection = function () {
if (!this.database) {
return Promise.reject(new Error('Model is not registered in a database.'));
Expand All @@ -132,7 +132,7 @@ Model.getConnection = function () {
Model.getCollection = function () {
return this.getConnection()
.then(db => {
const name = result(this, 'collection');
const name = result(this.prototype, 'collection');

return db.collection(name);
});
Expand Down
20 changes: 19 additions & 1 deletion test/models.js
Original file line number Diff line number Diff line change
Expand Up @@ -221,5 +221,23 @@ test('remove all documents', async t => {
});

test('automatically set collection name', async t => {
t.is(Post.collection(), 'posts');
t.is(Post.prototype.collection(), 'posts');
});

test('override collection name', async t => {
const {db} = t.context;

class CustomPost extends mongorito.Model {
collection() {
return 'awesome_posts';
}
}

db.register(CustomPost);

const post = new CustomPost({title: 'Greatness'});
await post.save();

const collections = await db._connection.collections();
t.deepEqual(collections.map(c => c.collectionName).sort(), ['comments', 'posts', 'awesome_posts'].sort());
});

0 comments on commit 4977e45

Please sign in to comment.